こんばんは。のるぼるのんです。
前回はLaravel-adminでForm画面にbelongsToのリレーションを設定出来る、セレクトボックスを作成しました。
今回は多対多、belongsToManyのリレーションを設定出来るようにしましょう。
前回はproduct-categoryのリレーションを設定したので、product-tagのリレーションとします。
やることとしてはtag CRUDの作成、pivot tableの作成、リレーションの構築ですかね。まあぼちぼちやって行きましょう。
モデル、テーブル作成
1 2 |
php artisan make:model Tag -m // Tagモデル、migrationファイル作成 php artisan make:model ProductTag -m // ProductTagモデル、migrationファイル作成 |
migrationファイルを編集します。
create_tags_table.php
1 2 3 4 5 6 7 8 |
public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); } |
create_product_tag_table.php
make:model -m でmigrationファイルを作成すると、モデル名の複数系となります。ピボットテーブルには単数形を使用するので、ファイル、テーブル名をproduct_tagとしてください。
1 2 3 4 5 6 7 8 |
public function up() { Schema::create('product_tag', function (Blueprint $table) { $table->increments('id'); $table->integer('product_id'); $table->integer('tag_id'); }); } |
Tag CRUDを作成
コントローラー作成
1 |
php artisan admin:make TagController --model=App\\Tag |
作成するコントローラーは、Tagの分だけでOKです。ピボットテーブルは表示させませんので。
routes.phpに ルーティングを追記
1 |
$router->resource('tags', TagController::class); |
タグを追加しました。
Product.php、ProcductController.phpを編集
Product.php
リレーションを追加
1 2 3 4 |
public function tag() { return $this->belongsToMany('App\Tag'); } |
ProductController.php
formにmultipleSelectを追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
protected function form() { $categories = Category::pluck('name', 'id'); $tags = Tag::pluck('name', 'id'); $form = new Form(new Product); $form->text('name', 'Name'); $form->image('photo', 'Photo'); $form->number('price', 'Price'); $form->select('category_id', 'Category')->options($categories); $form->multipleSelect('tag')->options($tags); // 追記します。'tag'とすることでtag()で指定したリレーションを使用します。 return $form; } |
一覧表示がバグるのはわかっているので、gridも編集します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
protected function grid() { $grid = new Grid(new Product); $grid->id('Id'); $grid->name('Name'); $grid->photo('Photo')->image(); $grid->price('Price'); $grid->category()->name('Category'); $grid->tag()->display(function ($tag) { // spanを使用し、ラベルを作成します $tag = array_map(function ($tag) { return "<span class='label label-success'>{$tag['name']}</span>"; }, $tag); return join(' ', $tag); }); return $grid; } |
実行してみます。
form、一覧画面も作成出来ました!
モデルにリレーションを記述するのみで、適切なピボットテーブルに保存、更新処理をしてくれるようですので、記述量が少なくてすみますね!
Laravel-adminはphpコード記述ベースで機能を追加出来るので、サクサク機能を追加できますね!
コメントを書く