# Laravel でカテゴリー作成 テーブル構築と再帰クエリ

環境

  • Laravel 10

コマンドでモデル、マイグレーションとコントローラー作成

php artisan make:model Category -mc

マイグレーション内容編集

データベースが再帰的なクエリをサポートする必要があります

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

class CreateCategoriesTable extends Migration
{
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->foreign('parent_id')->references('id')->on('categories');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('categories');
    }
}

マイグレーションかける

php artisan migrate

モデルファイル編集

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name', 'parent_id'];

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function descendants()
    {
        return $this->hasMany(Category::class, 'parent_id')->with('descendants');
    }
}

# コントローラーからカテゴリ一覧など取得

descendants メソッドを使って再帰的に子孫を含めたツリーを取得

use App\Models\Category;

// 親カテゴリのみ取得
$parentCategories = Category::whereNull('parent_id')->with('descendants')->get();

// すべてのカテゴリ(ツリー構造)
$allCategories = Category::with('descendants')->get();
2023-12-04

同じタグを持つ記事をピックアップしました。