they share single id of unique record.
$ php artisan make:model Video -m
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
$ php artisan make:model Tag -m
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
$ php artisan make:model Taggable -m
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
class Tag extends Model
{
//
public function posts(){
return $this->norphByMany('App\Post', 'taggables');
}
public function videos(){
return $this->norphByMany('App\Video', 'taggables');
}
}
$php artisan migrate
mysql> insert into videos (name) values (‘the mule’);
Query OK, 1 row affected (0.01 sec)
mysql> insert into videos (name) values (‘coding’);
Query OK, 1 row affected (0.00 sec)
mysql> insert into tags (name) values (‘javascript’);
Query OK, 1 row affected (0.04 sec)
mysql> insert into tags (name) values (‘php’);
Query OK, 1 row affected (0.01 sec)
mysql> insert into taggables (tag_id, taggable_id, taggable_type) values (1, 1,’App\Video’);
Query OK, 1 row affected (0.00 sec)
mysql> insert into taggables (tag_id, taggable_id, taggable_type) values (2, 1,’App\Post’);
Query OK, 1 row affected (0.01 sec)
Route::get('/post/tags', function(){
$post = Post::find(1);
foreach($post->tags as $tag){
echo $tag->name;
}
});
Route::get('/tag/post', function(){
$tag = Tag::find(1);
foreach($tag->posts as $post){
$echo $post->title;
}
});
polymorphic は、テーブル関係が複雑なので復習が必要だ