Polymorphic relation

Polymorphicの例は、staffの写真と商品の写真をphotosというテーブルで管理し、staffと商品を連携させることです。

$ php artisan make:model Staff -m

public function up()
    {
        Schema::create('staff', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

$ php artisan make:model Product -m

Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

$ php artisan make:model Photo -m

Schema::create('photos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('path');
            $table->integer('imageable_id');
            $table->string('imageable_type');
            $table->timestamps();
        });

$ php artisan migrate

Photo.php

public function imageable(){
    	return $this->morphTo();
    }

Staff.php, Product.php

public function photos(){
    	return $this->morphMany('App\Photo', 'imageable');
    }

staffsとproductsのテーブルにレコード挿入
mysql> insert into staff (name) values (‘peter’);
Query OK, 1 row affected (0.06 sec)

mysql> insert into staff (name) values (‘john’);
Query OK, 1 row affected (0.00 sec)

mysql> insert into product (name) values (‘laravel’);
ERROR 1146 (42S02): Table ‘polymorphic.product’ doesn’t exist
mysql> insert into products (name) values (‘laravel’);
Query OK, 1 row affected (0.01 sec)

mysql> insert into products (name) values (‘cake’);
Query OK, 1 row affected (0.00 sec)

Route::get('/create', function(){

	$staff = Staff::find(1);
	$staff->photos()->create(['path'=>'example.jpg']);

});

read

Route::get('/read', function(){

	$staff = Staff::findOrFail(1);

	foreach($staff->photos as $photo){
		return $photo->path;
	}

});

update

Route::get('/update', function(){

	$staff = Staff::findOrFail(1);

	$photo = $staff->photos(1)->whereId(2)->first();

	$photo->path = "update exampl.jpg";
	$photo->save();
});

delete

Route::get('/delete', function(){

	$staff = Staff::findOrFail(1);
	$staff->photos()->delete();
});

connect

Route::get('/assign', function(){

	$staff = Staff::findOrFail(1);

	$photo = Pohoto::findOrFail(3);

	$staff->photos()->save($photo);

});