Laravel:为什么不工作belongsTo()?

时间:2018-01-10 11:22:17

标签: php laravel laravel-5.5

我必须在视图中打印所有带有发件人姓名的邮件。我有这个代码的模型收件箱:

protected $fillable = ['id', 'subject', 'message', 'sender', 'recipient', 'seen', 'show', 'trashed', 'created_at'];

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

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

我返回并打印$message->sender->name给出错误Trying to get property of non-object$message->sender = sender id。使用发件人ID我必须从users表中获取发件人名称。

1 个答案:

答案 0 :(得分:3)

您需要为这些关系选择其他名称,因为您已经具有相同名称的属性。

public function messageSender()
{
    return $this->belongsTo(User::class, 'sender');
}

public function messageRecipient()
{
    return $this->belongsTo(User::class, 'recipient');
}

或将列名更改为sender_idrecipient_id