我有一个User
表,需要允许用户拥有父用户.
该表将包含以下字段:
id
parent_id
email
password
如何在Eloquent ORM中定义这种自引用关系?
我使用你的确切数据库表取得了一些成功.
用户模型:
class User extends Eloquent { protected $table = 'users'; public $timestamps = false; public function parent() { return $this->belongsTo('User', 'parent_id'); } public function children() { return $this->hasMany('User', 'parent_id'); } }
然后我可以在我的代码中使用它,如下所示:
$user = User::find($id); $parent = $user->parent()->first(); $children = $user->children()->get();
尝试一下,让我知道你是怎么过的!