为什么我在尝试访问"$comment->users->username"时遇到"Trying to get property 'username' of non-object"?



我正在尝试获取发表评论的用户的用户名,但是,我一直在尝试获得"非对象"的属性'username'错误。我相信我的人际关系做得正确,但我可能错了。

我的桌子:

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

用户模型:

class User extends Model implements Authenticatable
{
    public function comments(){
        return $this->hasMany('AppComment');
    }
}

我得到这样的评论:

$comments = Comment::with('users')->where('image_id', $id)->get();

然后尝试在这样的视图中循环循环:

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ $comment->users->username }}</p>
@endforeach

当我dd($注释)时,我会看到:

 #relations: array:1 [▼
        "users" => null
 ]

我不确定为什么是无效的。

尝试此

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

获取评论

$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

尝试以这种方式:

@foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ $comment->users["username"] }}</p>
@endforeach
@foreach($comments as $comment)
<p>{{ $comment->comment }}</p>
<p>{{ optional($comment->users)->username}}</p> 
@endforeach

尝试这种方法。

最新更新