Laravel 获取数据自动无限分类

2022-03-30  本文已影响0人  囧囧的猪

今天正好在做一个分类的模块,前端需要一个处理好的数据结构,大致如下:

[
  {
    id: 1,
    name: '分类1',
    children: [
      {
          id: 2,
          name: '分类1-1',
          children: [
            ....
          ]
      }
    ]
  },
  {
    id: 2,
    name: '分类2',
    children: [
      {
          id: 4,
          name: '分类2-1',
          children: [
            ....
          ]
      }
    ]
  }
]

数据表的迁移文件(migration) 注:我用的是laravel9,所以迁移文件可能与你的不一样:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('title')->default('')->comment('名称');
            $table->string('name')->default('')->unique()->comment('标识');
            $table->unsignedBigInteger('parent_id')->default(0)->comment('父级ID');
            $table->unsignedInteger('order')->default(0)->comment('排序');
            $table->timestamps();
        });
        DB::statement("ALTER TABLE `categories` COMMENT '分类表'");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
};

本来想着写一个递归函数做处理,结果无意中发现laravel的orm可以支持无限级获取数据。具体如下:

在Controller中代码:

<?php
// CategoryController.php
namespace App\Http\Controllers

use App\Http\Controllers\Controller;
use App\Models\Category;

class CategoryController extends Controller
{
  public function categoryTree(Request $request): AnonymousResourceCollection
    {
        $query = Category::with('children')
          ->where(['parent_id' => 0])->orderBy('order')->get();
        return CategoryResource::collection($query);
    }
}

在Model中代码:

<?php
// Category.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'name',
        'parent_id',
        'order',
    ];

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id','id')
            ->with('children')->orderBy('order');
    }
}

这样在前端调用接口时,返回的数据结构就是上面已经自动处理好的分类结构了,超级简单。

希望可以帮到需要的朋友 (笑脸)

上一篇下一篇

猜你喜欢

热点阅读