Laravel 5多级别类别 [英] Laravel 5 multi level category

查看:92
本文介绍了Laravel 5多级别类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有2张桌子category& subcategory一切正常,但是我需要另一个级别的子类别,例如category->sub->sub,我试图找到一个合理的解决方案,最后得到一堆包装来为我处理. >

现在的问题是

i currently i have 2 tables category & subcategory and everything works just fine, but i need another level of sub category which will be like category->sub->sub for that matter i tried to find a reasonable solution and i end up with bunch of packages to handle that for me.

  1. 我是否必须删除类别表及其与我的关系 在尝试任何软件包之前还是应该在当前表的顶部添加软件包的其他方式?
  2. 根据您的经验,最适合我的包装是什么?
  1. do i have to delete my category tables and their relations to my another modes before i try any package or i should just add package top of my current tables?
  2. what is the best package for my purpose base on your experience?

提前谢谢.

推荐答案

您无需依赖于软件包即可实现此目的.

You don't need to depend on packages to implement this.

您可以按照以下方式设计categories表:

You can design your categories table like following:

|----------|------------|---------------|
|    id    |    name    |  category_id  |
|----------|------------|---------------|

此处category_id是可空字段,并且引用了categories表的id的外键.

Here category_id is nullable field and foreign key referenced to id of categories table.

对于类别category_id,该字段将为NULL,对于子类别category_id,该字段将为其父类别ID.对于子子类别,category_id将是父子类别ID.

For category category_id field will be NULL and for sub-category category_id will be it's parent category id. For sub sub category, category_id will be parent sub category id.

在模型中,您可以编写如下关系:

In model, you can write relation like following:

Category.php

Category.php

/**
 * Get the sub categories for the category.
 */
public function categories()
{
    return $this->hasMany(Category::class);
}

现在,您可以获取诸如$category->categories之类的子类别.

Now you can get your sub categories like $category->categories.

N.B:您不需要subcategory表,只需一个表即可完成工作.

N.B: You don't need the subcategory table, Only one table will do the work.

更新-显示产品类别

更新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);
}

现在,您需要获取产品类别及其所有父项.从父母到孩子,这将是一系列类别.然后,您可以根据需要显示.

Now, you need to get product category and all of its parents. It'll be an array of categories from parents to child. Then you can show as you wish.

$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>';
}

这篇关于Laravel 5多级别类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆