[英]Laravel Eloquent BelongTo Model Access fails
I am trying to get data by using Laravel Eloquent HasMany (reverse) relationship but I am not getting access. 我正在尝试通过使用Laravel Eloquent HasMany(反向)关系获取数据,但是我没有访问权限。 Whenever I try, it shows Trying to get property 'name' of non-object
每当我尝试时,它都显示试图获取非对象的属性“名称”
I have two models. 我有两个模型。 Category and Article .
类别和文章 。 Category hasMany Articles .
类别有许多 文章 。 Here are the models:
这些是模型:
Category Model 分类模型
protected $fillable = [
'user_id', 'name',
];
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Article Model 文章模型
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');
}
Article Controller 物品管制员
public function pendingposts()
{
$user = Auth::user();
$articles = Article::all();
return view('admin.article.pending-posts')->with(['user' => $user, 'articles' => $articles]);
}
View Blade (admin.article.pending-posts) 查看刀片 (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
here in blade, I can not access category through eloquent BelongsTo feature and I am not getting the reason behind getting the message: 在刀片中,我无法通过雄辩的BelongsTo功能访问类别,并且我也没有得到消息背后的原因:
ErrorException (E_ERROR) Trying to get property 'name' of non-object (View: C:\\xampp\\htdocs\\joliadmin\\resources\\views\\admin\\article\\pending-posts.blade.php)
ErrorException(E_ERROR)试图获取非对象的属性“名称”(视图:C:\\ xampp \\ htdocs \\ joliadmin \\ resources \\ views \\ admin \\ article \\ pending-posts.blade.php)
You should try this: 您应该尝试这样:
public function pendingposts()
{
$user = Auth::user();
$articles = Article::with('category')
->where('status', 'submitted')
->sortByDesc('updated_at')
->get();
return view('admin.article.pending-posts')->with(compact('user', 'articles'));
}
@foreach($articles as $article)
<tr>
<td>{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
@endforeach
Updated Answer 更新的答案
Category Model 分类模型
protected $fillable = [
'user_id', 'name',
];
public function article()
{
return $this->hasMany('App\Models\Article');
}
it worked after changing 'Article' tables 'category' column in 'category_id'. 在更改“ category_id”中的“ Article”表,“ category”列后,它起作用了。 Thanks for helping.
感谢您的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.