如何在雄辩的Orm中实现自引用(parent

编程入门 行业动态 更新时间:2024-10-07 08:24:26
本文介绍了如何在雄辩的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

本文发布于:2023-10-23 02:30:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519477.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:雄辩   如何在   parent   Orm

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!