我正在尝试在文章中回显用户的名称,并且得到ErrorException Trying to get property of non-object
。这是我的代码:
模型(我也有一个用户模型):
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('User');
}
protected $table = 'tcity_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'];
}
控制器:
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
模型中有一个字段。我想念什么吗?
更新:当我尝试dschu用户说的是时{{ dd( $article->postedBy) }}
,我得到了该用户的ID。
问题是您的关系和数据库中的字段似乎具有相同的名称(postedBy)。
您应该有一个名为user_id的字段,而不是postedBy(或与userId保持一致)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句