且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在雄辩的Orm中实现自引用(parent_id)模型

更新时间:2023-01-29 13:50:51

使用您确切的数据库表,我获得了一些成功.

I had some success like this, using your exact DB table.

用户模型:

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

}

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

and then I could use it in my code like this:

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

$parent   = $user->parent()->first();
$children = $user->children()->get();

尝试一下,让我知道你的生活吧!

Give that a try and let me know how you get on!