我正在尝试获取发表评论的用户的用户名,但是,我不断收到“尝试获取非对象的属性'用户名'”错误。我相信我的人际关系正确无误,但我可能错了。
我的桌子:
Table: Users
Columns: id, username, password
Table: Comments
Columns: id, user_id, image_id, comment
评论模型:
class Comment extends Model
{
public function users(){
return $this->belongsTo('App\User');
}
}
用户模型:
class User extends Model implements Authenticatable
{
public function comments(){
return $this->hasMany('App\Comment');
}
}
我收到这样的评论:
$comments = Comment::with('users')->where('image_id', $id)->get();
然后尝试在这样的视图中遍历它们:
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ $comment->users->username }}</p>
@endforeach
当我dd($ comments)时,我看到:
#relations: array:1 [▼
"users" => null
]
我不确定为什么它为空。
答案 0 :(得分:1)
尝试一下
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ !empty($comment->users->username) ? $comment->users->username : '' }}</p>
@endforeach
我也建议您将关系名称users
更改为user
class Comment extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
}
获取评论
$comments = Comment::with('user')->where('image_id', $id)->get();
在视野中
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
@if(!empty($comment->user))
<p>{{ $comment->user->username }}</p>
@endif
@endforeach
答案 1 :(得分:1)
尝试这种方式:
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ $comment->users["username"] }}</p>
@endforeach
答案 2 :(得分:0)
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ optional($comment->users)->username}}</p>
@endforeach
尝试这种方法。