在模型中声明一对多的关系,关联表本身。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。请问这种写法是对的吗?为什么查不到关联模型呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
Tree 的完整实现:
参考:https://git.load-page.com/r/l...
belongsTo的用法和hasOne的效果是一样的,只是参数反过来。
使用
我考虑到你这可能只是基类,就好像我这个类一样,并不是直接用的,最好使用如下方法获取
final的类名:get_class($this)static::class因为
self的意思是__CLASS__,而非final的类把self换成static试试
把self:class改成$this就对了