Laravel 5 Laravel 5多级分类
我目前有两个表Laravel 5 Laravel 5多级分类,laravel-5,Laravel 5,我目前有两个表category&subcategory,一切都很好,但我需要另一个级别的子类别,就像category->sub->sub,我试图找到一个合理的解决方案,最后我得到了一堆包来帮我处理这个问题 现在的问题是 我是否必须删除我的类别表及其与我的类别表的关系 在我尝试任何软件包之前,是否需要另一种模式,或者我应该将软件包添加到当前表的顶部 根据你的经验,对我来说最好的包装是什么 提前感谢。您不需要依赖软件包来实现这一点 您可以按如下方式设计类别表: |----------|-------
category
&subcategory
,一切都很好,但我需要另一个级别的子类别,就像category->sub->sub
,我试图找到一个合理的解决方案,最后我得到了一堆包来帮我处理这个问题
现在的问题是
提前感谢。您不需要依赖软件包来实现这一点 您可以按如下方式设计
类别
表:
|----------|------------|---------------|
| id | name | category_id |
|----------|------------|---------------|
这里的category\u id
是可为空的字段,外键引用到categories
表的id
对于类别category\u id
字段将为NULL
,对于子类别category\u id
将为其父类别id。对于子类别,category\u id
将为父子类别id
在模型中,您可以编写如下关系:
|----------|------------|---------------|
| id | name | category_id |
|----------|------------|---------------|
Category.php
/**
* Get the sub categories for the category.
*/
public function categories()
{
return $this->hasMany(Category::class);
}
现在您可以获得子类别,如$category->categories
注意:您不需要子类别
表,只有一个表可以完成这项工作
更新-显示产品类别
更新Category.php
:
/**
* Get the parent category that owns the category.
*/
public function parent()
{
return $this->belongsTo(Category::class);
}
/**
* Get the category that owns the product.
*/
public function category()
{
return $this->belongsTo(Category::class);
}
在Product.php
中:
/**
* Get the parent category that owns the category.
*/
public function parent()
{
return $this->belongsTo(Category::class);
}
/**
* Get the category that owns the product.
*/
public function category()
{
return $this->belongsTo(Category::class);
}
现在,您需要获取产品类别及其所有父项。它将是一个从父母到孩子的类别数组。然后你可以随心所欲地表演
$category = $product->category;
$categories = [$category];
while (!is_null($category) && !is_null($category = $category->parent)) {
$categories.unshift($category);
}
// $categories = ['parent category', 'sub category', 'sub sub category' ..]
按顺序显示类别标题
foreach ($categories as $category) {
echo $category->title . '<br>';
}
foreach($categories作为$category){
echo$category->title.“
”;
}
很有趣,所以对于子类别(第三级),我得到第一级或第二级的id作为类别id
第二级category\u id
始终是指category的父id。您好,我仍在按照您建议的方式工作,我想知道如何显示我的帖子/产品类别层次结构?e、 g.我正在访问我的产品,我想显示该产品属于默认类别
或默认类别->第一个孩子
我该怎么做?这不起作用。{code>{ucfirst($product->category->categories->title)}hi,如果我最后在controller中使用你的foreach
,我会得到错误,当我在blade中使用它时,它只给我类别标题,没有任何父项。如果你的项目在源代码管理下,只需创建一个测试分支,完成后丢弃它。