0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Posted at

はじめに


多対多リレーションを操作するための中間テーブルについてのメモ。
//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();
        });
    }


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


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


//categoryモデル

    protected $guarded = [];

    protected $table = 'category';

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

中間テーブルの作成

//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();
        });
    }

マイグレーション

php artisan migrate

適当にデータを入れる。

//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);;
                }
    }
}


//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],
        ]);
    }
}

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

php artisan db:seed

完成。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?