本文介绍了如何在雄辩的Orm中实现自引用(parent_id)模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个User表,需要允许用户拥有一个父用户.
I have a User table and need to allow for users to have a parent user.
该表将具有以下字段:
- id
- parent_id
- password
- id
- parent_id
- 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
发布评论