我必须在视图中打印所有带有发件人姓名的邮件。我有这个代码的模型收件箱:
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表中获取发件人名称。
答案 0 :(得分:3)
您需要为这些关系选择其他名称,因为您已经具有相同名称的属性。
public function messageSender()
{
return $this->belongsTo(User::class, 'sender');
}
public function messageRecipient()
{
return $this->belongsTo(User::class, 'recipient');
}
或将列名更改为sender_id
和recipient_id