ピボットテーブルの書き方のメモ　【Laravel】


#はじめに

<br>
多対多リレーションを操作するための中間テーブルについてのメモ。
<br>

```php
//productsテーブル
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->string('details')->nullable();
            $table->integer('price');
            $table->text('description');
            $table->boolean('featured')->default(false);
            $table->timestamps();
        });
    }
```
<br>
<br>

```php
//productsモデル
    public function categories()
{
    return $this->belongsToMany('App\Models\Category');
}
```
<br>
<br>

```php
//categoryテーブル
    public function up()
    {
        Schema::create('category', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });
    }
```
<br>
<br>

```php
//categoryモデル

    protected $guarded = [];

    protected $table = 'category';

    public function products()
    {
        return $this->belongsToMany('App\Models\Product');
    }
```
<br>


中間テーブルの作成

```php
//category_productテーブル

   public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->id();
            
            $table->foreignId('product_id')->references('id')
                  ->on('products')->onDelete('cascade')->nullable();

            $table->foreignId('category_id')->references('id')
                  ->on('category')->onDelete('cascade')->nullable();
                  
            $table->timestamps();
        });
    }
```
<br>

マイグレーション

```php
php artisan migrate
```
<br>

適当にデータを入れる。

```php
//ProductsTableSeeder
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Product;
class ProductsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
                // Laptops
                for ($i=1; $i <= 30; $i++) {
                    Product::create([
                        'name' => 'Laptop '.$i,
                        'slug' => 'laptop-'.$i,
                        'details' => [13,14,15][array_rand([13,14,15])] . ' inch, ' . [1, 2, 3][array_rand([1, 2, 3])] .' TB SSD, 32GB RAM',
                        'price' => rand(149999, 249999),
                        'description' =>'Lorem '. $i . ' ipsum dolor sit amet, consectetur adipisicing elit. Ipsum temporibus iusto ipsa, asperiores voluptas unde aspernatur praesentium in? Aliquam, dolore!',
                        // 'image' => 'products/dummy/laptop-'.$i.'.jpg',
                        // 'images' => '["products\/dummy\/laptop-2.jpg","products\/dummy\/laptop-3.jpg","products\/dummy\/laptop-4.jpg"]',
                    ])->categories()->attach(1);;
                }
    }
}

```
<br>

```php
//CategoriesTableSeeder
<?php

namespace Database\Seeders;

use App\Models\Category;
use Carbon\Carbon;
use Illuminate\Database\Seeder;

class CategoriesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $now = Carbon::now()->toDateTimeString();

        Category::insert([
            ['name' => 'Laptops', 'slug' => 'laptops', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'Desktops', 'slug' => 'desktops', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'Mobile Phones', 'slug' => 'mobile-phones', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'Tablets', 'slug' => 'tablets', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'TVs', 'slug' => 'tvs', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'Digital Cameras', 'slug' => 'digital-cameras', 'created_at' => $now, 'updated_at' => $now],
            ['name' => 'Appliances', 'slug' => 'appliances', 'created_at' => $now, 'updated_at' => $now],
        ]);
    }
}
```
<br>

```php
//DatabaseSeeder
class DatabaseSeeder extends Seeder
{
 
    public function run()
    {
        $this->call([
            CategoriesTableSeeder::class,
            ProductsTableSeeder::class,
        ]);
    }
}
```

<br>


```php
php artisan db:seed
```

<br>

完成。