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

 用户d4k2wd8en1 发布于 2023-02-13 18:35

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

该表将包含以下字段:

id

parent_id

email

password

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

1 个回答
  • 我使用你的确切数据库表取得了一些成功.

    用户模型:

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

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

    $user     = User::find($id);
    
    $parent   = $user->parent()->first();
    $children = $user->children()->get();
    

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

    2023-02-13 18:39 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有