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

Laravel: Why not work belongsTo()?

我必须打印所有显示发件人姓名的邮件。我有带有此代码的模型收件箱:

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');
}

我 return 并打印 $message->sender->name 给定错误 Trying to get property of non-object$message->sender = sender id。使用发件人 ID,我必须从用户 table 处获取发件人姓名。

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

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

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

或将列名称更改为 sender_idrecipient_id