我有一个包含所有类别文章帖子的列表。我想在列表中的每个帖子中显示的类别标签,我尝试这样的:在帖子记录中获取类别名称
<article class="post bg z-depth-1">
<?php foreach ($article_list as $article): ?>
<div class="post-img">
<a href="post.html">
<img class="retina" src="{{ asset('image/' . $article->image) }}" width="820" height="500" alt="Post Image">
</a>
</div>
<div class="post-content">
<div class="post-header center-align">
<div class="tags">
<a href="#">{{ $article->category->title }}</a></div>
<h2 class="post-title"><a href="post.html">{{ $article->title }}</a></h2>
<div class="date">Posted on {{ Carbon\Carbon::parse($article->created_at)->format('F j, Y') }}</div>
</div>
<div class="post-entry">
<p>sss</p>
</div>
<div class="post-footer">
<div class="post-footer-item">
<a href="post.html" class="link"><span class="text">Read More</span> <i class="fa fa-arrow-circle-right"></i></a>
</div>
</div>
</div><!-- .post-content -->
<?php endforeach ?>
</article><!-- .post -->
,它给了我错误Undefined property: stdClass::$category
,我不知道为什么,我已经定义每个模型文章和类别的关系。谢谢您的帮助!
在文章模型:
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
在分类模式:
public function article() {
return $this->hasMany('App\Article', 'category_id');
}
控制器:
public function index() {
$article_list = Article::all();
return view('article/index', compact('article_list', $article_list));
}
请出示你的人际关系。 – GabMic
@GrowingDev我已在您的模型中更新了我的问题 –
,请删除'category_id'字段并尝试。 – GabMic