如何在雄辩的Orm中实现自引用(parent_id)模型 [英] How to implement a self referencing (parent_id) model in Eloquent Orm
本文介绍了如何在雄辩的Orm中实现自引用(parent_id)模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个User
表,需要允许用户拥有一个父用户.
I have a User
table and need to allow for users to have a parent user.
该表将具有以下字段:
-
id
-
parent_id
-
email
-
password
id
parent_id
email
password
我该如何在雄辩的ORM中定义这种自引用关系?
How would I define this self referencing relationship in Eloquent ORM?
推荐答案
使用您确切的数据库表,我获得了一些成功.
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!
这篇关于如何在雄辩的Orm中实现自引用(parent_id)模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文