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

原文地址:https://www.cnblogs.com/lxwphp/p/10743574.html