如何在Eloquent Orm中实现自引用(parent_id)模型

Din*_*amy 18 php laravel eloquent

我有一个User表,需要允许用户拥有父用户.

该表将包含以下字段:

  • id
  • parent_id
  • email
  • password

如何在Eloquent ORM中定义这种自引用关系?

mst*_*rdy 39

我使用你的确切数据库表取得了一些成功.

用户模型:

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');
    }

}
Run Code Online (Sandbox Code Playgroud)

然后我可以在我的代码中使用它,如下所示:

$user     = User::find($id);

$parent   = $user->parent()->first();
$children = $user->children()->get();
Run Code Online (Sandbox Code Playgroud)

尝试一下,让我知道你是怎么过的!