如何在laravel 5.4中实现一个无限级分类

今天就跟大家聊聊有关如何在laravel 5.4中实现一个无限级分类,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

1、建立表

php artisan make:migration create_category_table --create=category

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

建入:

<?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

php artisan make: model Category -m
<?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、调用

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

$categorys->allChildrenCategorys;

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

看完上述内容,你们对如何在laravel 5.4中实现一个无限级分类有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。