dongyou8087 2019-04-05 19:13
浏览 34

试图获取非对象Laravel的属性用户

I have model review with:

public function shop()
{
    return $this->belongsTo(Shop::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}

public function parent()
{
    return $this->belongsTo(static::class, 'id', 'parent_id');
}

public function isParent()
{
    return !$this->parent_id;
}

public function children()
{
    return $this->hasMany(static::class, 'parent_id');
}

public function sendReviewNotification()
{
    if ($this->isParent()) {
        $this->shop->owner->sendReviewParentNotification($this);
    } else {
        if ($this->user->is($this->parent->user)) {
            $this->shop->owner->sendReviewCommentNotification($this);
        } else {
            $this->parent->user->sendReviewCommentNotification($this);
        }
    }
}

When I add a child comment to a parrent comment I get error: 'Trying to get property 'user' of non-object', in ReviewObserver I call sendReviewNotification like this:

public function created(Review $review)
{
    $review->sendReviewNotification();
}

When I add parent module. Than all working, but when I add a child comment than I get this error. Why parent relation not working?

  • 写回答

1条回答 默认 最新

  • douluxia0606 2019-04-05 19:16
    关注

    You should pass the foreign key as the second parameter, not the id:

    public function parent()
    {
        return $this->belongsTo(Parent::class, 'parent_id');
    }
    

    Docs:

    Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. You may pass a custom key name as the second argument to the belongsTo method

    For more info: click here

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大