我试图通过使用Laravel雄辩的HasMany (反向)关系获取数据,但我无法访问。每当我尝试时,它都会显示试图获取非对象的属性“名称”。
我有两个模特。分类和文章。分类 hasMany 文章。以下是模型:
范畴模型
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]);
}查看刀片(管理。文章。待定-张贴)
@foreach($articles->where('status', 'submitted')->sortByDesc('updated_at') as $article)
<tr>
<td >{{ $article->headline }}</td>
<td>{{ $article->category->name }} </td>
</tr>
@endforeach在刀片中,我无法通过雄辩的BelongsTo特性访问类别,也无法理解获取消息的原因:
试图获取非对象的属性“名称”(View: C:\xampp\htdocs\joliadmin\resources\views\admin\article\pending-posts.blade.php) )的ErrorException (E_ERROR)
发布于 2019-01-10 11:36:31
你应该试试这个:
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最新答案
范畴模型
protected $fillable = [
'user_id', 'name',
];
public function article()
{
return $this->hasMany('App\Models\Article');
}发布于 2019-01-14 07:29:13
在更改“类别_id”中的“文章”表“类别”列后,它工作了。谢谢你的帮助。
https://stackoverflow.com/questions/54127827
复制相似问题