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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lxw1844912514

你的打赏就是对我最大的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值