Laravel-子类别显示在主要类别下 [英] Laravel - Sub-categories display under Main categories
问题描述
您好
我对类别和子类别有一个问题
我有这样的表:
Hi there
I have one problem with categories and sub-categories
I have table like:
ID ------名称---- ParentID
1 ------- A ---------- 0
2 ------- B ---------- 0
3 ------- C ---------- 1
我已经显示了A B C ok.但我需要它会像这样显示:
A
-C
B
ID----- Name---- ParentID
1 ------- A ---------- 0
2 ------- B ---------- 0
3 ------- C ---------- 1
I have showing A B C ok . But i need it will show like this:
A
-- C
B
只是有一个问题,找不到方法(在父项下创建子类别)
Just have problem with dont find the way to do this (to make sub categories under parent)
注意:我在Views中成功进行了make查询,但是我认为它不好.
我想找到更好的方法
非常感谢
Note: i have success with make query in Views, but i think its not good .
I would like to find better way
Thank you very much
推荐答案
使用雄辩,您可以使用hasMany()
关系将表与其自身关联.
Using Eloquent you can use a hasMany()
relationship to relate the table to itself.
尝试在模型上创建新方法,如下所示:
Try creating a new method on your model, like so:
class Category extends Eloquent
{
...
public function children()
{
return $this->hasMany('Category','ParentId');
}
}
然后,您应该可以获取任何给定ID的子类别列表.
Then you should be able to get a list of sub categories for any given ID.
$categories = Category::where('ID','=','1')->with('children')->get();
或者,由deczo在注释中建议的查询要简单得多,我建议改为使用它.
Alternatively, the query suggested by deczo in the comments is a lot simpler, I would recommend using this instead.
Category::with('children')->find(1);
这篇关于Laravel-子类别显示在主要类别下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!