Polymorphic many to many relation(morphToMany)

The last of laravel database relation.

$ php artisan make:model Post -m
$ php artisan make:model Video -m
$ php artisan make:model Tags -m

1
2
3
4
5
Schema::create('videos', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

$ php artisan make:model Taggable -m

1
2
3
4
5
6
7
Schema::create('taggables', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('tag_id');
            $table->integer('taggable_id');
            $table->string('taggable_type');
            $table->timestamps();
        });

$ php artisan migrate

Post.php, Video.php

1
2
3
4
protected $fillable = ['name'];
public function tags(){
    return $this->norphToMany('App\Tags', 'taggable');
}

Tags.php

1
2
3
4
class Tags extends Model
{
    protected $fillable = ['name'];
}

insert into tags (name) values (‘php’);
insert into tags (name) values (‘ruby’);
model name間違えた。。
alter table taggables change column tag_id tags_id int;

1
2
3
4
5
6
7
8
9
10
11
Route::get('/create', function(){
 
    $post = Post::create(['name'=>'my frist post']);
    $tag1 = Tags::findOrFail(1);
    $post->tags()->save($tag1);
 
    $video = Video::create(['name'=>'video.now']);
    $tag2 = Tags::findOrFail(2);
    $video->tags()->save($tag2);
 
});

read

1
2
3
4
5
6
7
Route::get('/read', function(){
 
    $post = Post::findOrFail(9);
    foreach($post->tags as $tag){
        echo $tag;
    }
});

update

1
2
3
4
5
6
7
Route::get('/update', function(){
 
    $post = Post::findOrFail(9);
    foreach($post->tags as $tag){
        $tag->whereId(1)->update(['name'=>'google']);
    }
});

delete

1
2
3
4
5
6
7
8
Route::get('/delete', function(){
 
    $post = Post::find(1);
 
    foreach($post->tags as $tag){
        $tag->whereId(1)->delete();
    }
});