我正在尝试通过使用 Laravel Eloquent HasMany(反向)关系来获取数据,但我无法访问。每当我尝试时,它都会显示Trying to get property 'name' of non-object
我有两个模型。类别和文章。类别有很多文章。以下是模型:
类别模型
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
文章模型
protected $fillable = [
'user_id', 'headline', 'summary', 'body', 'status', 'cover_image', 'image_caption', 'image_credit', 'cover_video', 'video_caption', 'video_credit', 'category', 'meta', 'tags',
];
public function category()
{
return $this->belongsTo('App\Models\Category','category');
}
文章控制器
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
查看刀片(admin.article.pending-posts)
@foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
@endforeach
在刀片中,我无法通过 eloquent BelongsTo 功能访问类别,也没有得到消息背后的原因:
ErrorException (E_ERROR) 试图获取非对象的属性“名称”(查看:C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php)