laravel中如何在模型中自关联?

举报
lxw1844912514 发表于 2022/03/29 00:57:24 2022/03/29
4.3k+ 0 0
【摘要】 https://segmentfault.com/q/1010000007926567 在模型中声明一对多的关系,关联表本身。parent_id对应父记录的id。我在sof中查阅到很多这样的写法: public function belongsToParent(){ return $this-&g...

https://segmentfault.com/q/1010000007926567

在模型中声明一对多的关系,关联表本身。parent_id对应父记录的id。我在sof中查阅到很多这样的写法:


         public function belongsToParent(){
            return $this->belongsTo(self::class, "parent_id");
         }
         public function hasManyChildren(){
            return $this->hasMany(self::class, "parent_id");
         }
     
    

但是我通过模型的with('belongsToParent')查不到关系,parent_id有值,关联的relations却为null。请问这种写法是对的吗?为什么查不到关联模型呢?

belongsTo的用法和hasOne的效果是一样的,只是参数反过来。


         public function parent()
         {
            return $this->hasOne(get_class($this), $this->getKeyName(), 'parent_id');
         }
         public function children()
         {
            return $this->hasMany(get_class($this), 'parent_id', $this->getKeyName());
         }
         ID  pid title
         1   0   中国
         2   1   广东省
         3   2   广州市
         4   2   深圳市
         5   3   白云区
         使用
         $a = Tree::with(['children'])->find(2);
         dd($a->children);
         输出 广州市 深圳市
     
    

我考虑到你这可能只是基类,就好像我这个类一样,并不是直接用的,最好使用如下方法获取final的类名:

  • get_class($this)

  • static::class

因为 self 的意思是 __CLASS__,而非final的类

把self换成static试试

把self:class改成$this就对了

文章来源: blog.csdn.net,作者:lxw1844912514,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/lxw1844912514/article/details/100028130

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

作者其他文章

评论(0

抱歉,系统识别当前为高风险访问,暂不支持该操作

    全部回复

    上滑加载中

    设置昵称

    在此一键设置昵称,即可参与社区互动!

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

    *长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。