- 追加された行はこの色です。
- 削除された行はこの色です。
[[Laravelめも]]
#contents
Laravelに限らずRDBでツリー構造を扱う方法はいくつかありますが、入れ子集合モデル(Nested Sets Model)⁠が有効なようです。~
CakePHPでもTreeBehaviorとして実装されています。
[[Laravel NestedSet:https://github.com/lazychaser/laravel-nestedset]]と[[Baum:https://github.com/etrepat/baum]]が有名所のようですが、Baumは2015年からメンテされていないようなので、Laravel NestedSetが選択肢になりそうです。
*インストール [#k56c58ec]
Composerにてインストールします。
$ composer require kalnoy/nestedset
vendor/kalnoy/nestedset/ 以下にインストールされます。
*テーブルの作成 [#e5627d38]
良く使われそうなカテゴリーを例として作成します。
$ php artisan make:migration create_categories_table
database/migrations/ 以下にファイルが生成されるので、こちらを編集します。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Kalnoy\Nestedset\NestedSet;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 32);
NestedSet::columns($table);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
$ php artisan migrate
*モデルの作成 [#zad2b7c2]
$ php artisan make:model Models/Category
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use NodeTrait;
protected $fillable = [
'name',
];
}
*テスト用データの作成 [#g1d38b40]
$ php artisan make:seeder CategoriesTableSeeder
database/seeds/ 以下にファイルが生成されます。
<?php
use Illuminate\Database\Seeder;
use App\Models\Category;
class CategoriesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$Category = new Category();
$Category->create(['name' => 'インテリア']);
$parent = $Category->create(['name' => 'キッチンツール']);
$parent->children()->create(['name' => '調理器具']);
$child_parent = $parent->children()->create(['name' => '食器']);
$child_parent->children()->create(['name' => 'フォーク']);
$Category->create(['name' => '新入荷']);
}
}
$ php artisan make:seeder CategoriesTableSeeder
*コントローラーの作成 [#k21d0d64]
$ php artisan make:controller CategoryController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Category;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get()->toTree();
return view('category', compact('categories'));
}
}
*ビューの作成 [#ke379de0]
@foreach ($categories as $category)
<div class="col-md-12">
<h3>{{ $category->name }}</h3>
<hr>
<div class="row">
@foreach ($category->children as $cats)
<div class="col-md-4">
<h4>{{ $cats->name }}</h4>
<hr>
@foreach ($cats->children as $cat)
<h5>{{$cat->name}}</h5>
@endforeach
</div>
@endforeach
</div>
</div>
@endforeach