码迷,mamicode.com
首页 > 其他好文 > 详细

Laravel 5.4 实现无限级分类

时间:2018-05-21 01:06:01      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:keyword   网上   int   support   min   namespace   tran   bottom   col   

最近在工作中遇到一个需求,是要在laravel 5.4中实现无限级分类,但发现网上这个的资料较少,所以只能自己来实现了,下面这篇文章主要给大家介绍了关于在laravel 5.4中实现无限级分类的方法示例,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

本文主要给大家介绍的是关于laravel 5.4中实现无限级分类的相关内容,分享出来供有需要的朋友们参考学习,下面话不多说,来一起看看详细的介绍吧。

方法如下:

1、建立表

1
php artisan make:migration create_category_table --create=category

在database/migrations/下找到你的迁移文件

建入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateCategoryTable extends Migration
{
 /**
 * Run the migrations.
 *
 * @return void
 */
 public function up()
 {
 Schema::create(‘categorys‘, function (Blueprint $table) {
  $table->increments(‘id‘);
  $table->integer(‘parent_id‘);
  $table->string(‘code‘);
  $table->string(‘name‘);
  $table->string(‘path‘);
  $table->timestamps();
 });
 }
  
 /**
 * Reverse the migrations.
 *
 * @return void
 */
 public function down()
 {
 Schema::dropIfExists(‘categorys‘);
 }
}
php artisan migrate

2、建Model 在app/Category.php

1
php artisan make: model Category -m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
  
namespace App;
  
use Illuminate\Database\Eloquent\Model;
  
class Category extends Model
{
 public function childCategory() {
 return $this->hasMany(‘App\Category‘, ‘parent_id‘, ‘id‘);
 }
  
 public function allChildrenCategorys()
 {
 return $this->childCategory()->with(‘allChildrenCategorys‘);
 }
}

3、调用

1
$categorys = App/Category::with(‘allChildrenCategorys‘)->first();

1
$categorys->allChildrenCategorys;

1
$categorys->allChildrenCategorys->first()->allChildrenCategorys;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者使用laravel能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

Laravel 5.4 实现无限级分类

标签:keyword   网上   int   support   min   namespace   tran   bottom   col   

原文地址:https://www.cnblogs.com/mouseleo/p/9065246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!