我正在尝试在文章中回显用户的名称,并且得到ErrorException: Trying to get property of non-object
。我的代码:
楷模
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
表 news
控制者
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
刀
{{ $article->postedBy->name }}
当我尝试删除刀片中的名称时,{{ $article->postedBy }}
它会输出id
,但是当我尝试在其中添加-> name时,会显示,Trying to get property of non-object
但name
我的表和User
模型中都有一个字段。我想念什么吗?
您的查询返回数组还是对象?如果将其转储出去,您可能会发现它是一个数组,而您需要的只是数组访问([])而不是对象访问(->)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句