今天正好在做一個(gè)分類的模塊,前端需要一個(gè)處理好的數(shù)據(jù)結(jié)構(gòu),大致如下:
[
{
id: 1,
name: '分類1',
children: [
{
id: 2,
name: '分類1-1',
children: [
....
]
}
]
},
{
id: 2,
name: '分類2',
children: [
{
id: 4,
name: '分類2-1',
children: [
....
]
}
]
}
]
數(shù)據(jù)表的遷移文件(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('標(biāo)識(shí)');
$table->unsignedBigInteger('parent_id')->default(0)->comment('父級(jí)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');
}
};
本來(lái)想著寫(xiě)一個(gè)遞歸函數(shù)做處理,結(jié)果無(wú)意中發(fā)現(xiàn)laravel的orm可以支持無(wú)限級(jí)獲取數(shù)據(jù)。具體如下:
在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');
}
}
這樣在前端調(diào)用接口時(shí),返回的數(shù)據(jù)結(jié)構(gòu)就是上面已經(jīng)自動(dòng)處理好的分類結(jié)構(gòu)了,超級(jí)簡(jiǎn)單。
希望可以幫到需要的朋友 (笑臉)