你不需要依赖包来实现它。
您可以设计您的categories 表,如下所示:
|----------|------------|---------------|
| id | name | category_id |
|----------|------------|---------------|
这里category_id 是可空字段,外键引用categories 表的id。
对于类别category_id,字段将是NULL,对于子类别category_id,将是它的父类别ID。对于子子类别,category_id 将是父子类别 ID。
在模型中,你可以写如下关系:
Category.php
/**
* Get the sub categories for the category.
*/
public function categories()
{
return $this->hasMany(Category::class);
}
现在您可以获取您的子类别,例如$category->categories。
注意:您不需要subcategory 表,只需一张表即可。
更新 - 显示产品类别
更新Category.php:
/**
* Get the parent category that owns the category.
*/
public function parent()
{
return $this->belongsTo(Category::class);
}
在Product.php:
/**
* 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>';
}