【发布时间】:2017-05-17 03:03:35
【问题描述】:
我尝试从我的文章中获取类别。
一个类别可以有多个子类别,但我只想要第一级。在我的数据库中,每个子类别都有一个 parent_id,存储在同一个表中。
我有一个方法 scopeFirstLevelItems 但我认为它在这里对我没有帮助?
public function scopeFirstLevelItems($query)
{
return $query->where('depth', '1')
->orWhere('depth', null)
->orderBy('lft', 'ASC');
}
可以从子类别中获取类别父级吗?
为了在我的控制器中获取类别,我试试这个
protected function index(Article $article)
{
$articles = Article::published()->paginate(8);
$category = Category::with('articles')->firstLevelItems()->where('id', $article->id)->get();
return view('pages.blog', [
'articles' => $articles,
'category' => $category
]);
}
在我看来
<a href="{{ $category->slug }}">{{ $category->name }}</a>
但它不起作用。
我的类别模型中有三个关系
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function articles()
{
return $this->hasMany('App\Models\Article');
}
你能帮帮我吗?谢谢
【问题讨论】:
-
我认为你需要
->orWhere('parent_id', null)而不是->orWhere('depth', null) -
你好@hassan,我已经编辑了我的问题。我的要求现在有点不同了
-
parent()和children()都指向同一个模型Category