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


    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就对了

  • 相关阅读:
    【工具】使用Google搜索的一些技巧
    git merge和rebase合并分支的区别
    《人月神话》读后感
    记录 Vue 中遇见的坑
    chrome信任http
    sed命令替换配置文件
    中控考勤机IP能ping通,但是同过接口连接不上的解决版本
    如何启动解压版的Tomcat6.0
    服务器获取客户端ip
    linux 增加权限
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15453429.html
Copyright © 2020-2023  润新知