试图获得非对象的属性 - Laravel 5

2022-08-30 10:47:21

我试图在我的文章中回显用户的名称,我得到了

错误异常:尝试获取非对象的属性

我的代码:

模型

1. News

    class News extends Model
    {
      public function postedBy()
      {
         return $this->belongsTo('App\User');
      }
      protected $table = 'news';
      protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
    }

2. User

    class User extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;

        protected $table = 'users';

        protected $fillable = ['name', 'email', 'password'];

        protected $hidden = ['password', 'remember_token'];

    }

图式

桌子users

enter image description here

桌子news

enter image description here

控制器

public function showArticle($slug)
    {
        $article = News::where('slug', $slug)->firstOrFail();
        return view('article', compact('article'));
    }

叶片

{{ $article->postedBy->name }}

当我尝试删除边栏选项卡中的名称时,它会输出 ,但是当我尝试添加 ->name 时,它会显示 nameUser' 模型。我错过了什么吗?{{ $article->postedBy }}idTrying to get property of non-object but I have a field in my table and a


答案 1

您的查询是返回数组还是对象?如果将其转储出来,您可能会发现它是一个数组,您所需要的只是数组访问 ([]) 而不是对象访问 (->)。


答案 2

我通过使用Jimmy Zoto的答案并向我的.在这里:belongsTo

首先,正如Jimmy Zoto所建议的那样,我的代码在刀片中来自

$article->poster->name 

$article->poster['name']

接下来是在 my 中添加第二个参数,从belongsTo

return $this->belongsTo('App\User');

return $this->belongsTo('App\User', 'user_id');

其中是我在新闻表中的外键。user_id


推荐