【问题标题】:Why am I getting "Trying to get property 'username' of non-object" when trying to access "$comment->users->username"?为什么我在尝试访问“$comment->users->username”时收到“尝试获取非对象的属性 'username'”?
【发布时间】:2019-05-19 10:07:29
【问题描述】:

我正在尝试获取已发布 cmets 的用户的用户名,但是,我不断收到“尝试获取非对象的属性‘用户名’”错误。我相信我的关系是正确的,但我可能错了。

我的桌子:

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

我得到这样的 cmets:

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

然后尝试像这样在视图中循环它们:

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

当我 dd($cmets) 时,我看到了:

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

我不知道为什么它是空的。

【问题讨论】:

标签: php laravel eloquent


【解决方案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');
    }
}

获取cmets

$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

【讨论】:

  • 你试试吗??
【解决方案2】:

试试这个方法:

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

【讨论】:

    【解决方案3】:
    @foreach($comments as $comment)
    <p>{{ $comment->comment }}</p>
    <p>{{ optional($comment->users)->username}}</p> 
    @endforeach
    

    试试这个方法。

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2019-09-11
      相关资源
      最近更新 更多