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

问题描述

你好,我有一个新项目.我想在这个项目中建立一个多类别的系统.例子类别 -子类别 -子子类别 -subsubsubsubcategory -subsubsubsubsubcategory -subsubsubcategory.等等.

Hello there I have a new project. I would like to build a multi-category system in this project.ExampleCategory -Subcategory -Sub sub category -Subsubsubcategory -Subsubsubsubcategory -Subsubsubcategory.and so on..

我使用laravel 5.4版本.怎么做?

I use laravel 5.4 version. How to make this?

推荐答案

制作一个Category模型和一个附带的表.在表中添加parent_id.现在,我们假设您具有以下类别:

Make a Category Model and a table that goes with. In the table add parent_id. Now you let's assume you have these categories:

Name      id       parent_id
cat1      1        NULL
cat2      2        1
cat3      3        2
cat4      4        3

您知道了,现在cat4cat3的子类别,而cat3cat2的子类别,而cat2cat1的子类别.

You get it, now cat4 is a subcategory of cat3 which is a sub of cat2 which is a sub of cat1.

您可以在模型中完成

public function parent() {
    return $this->belongsTo('App\Category', 'parent_id'); get parent category
}

public function children() {
    return $this->hasMany('App\Category', 'parent_id'); //get all subs. NOT RECURSIVE
}

尝试一下,看看效果如何.

Give this a try and see how it goes.

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

07-22 18:47
查看更多