What is your question exactly? Seed them just like any other table. You can use Eloquent for this or simple inserts, whatever suits you.
Jan 29, 2015
16
Level 1
How do I seed many-to-many polymorphic relationships?
Let's just use the examples in the documentation.
posts
id - integer
name - string
videos
id - integer
name - string
tags
id - integer
name - string
taggables
tag_id - integer
taggable_id - integer
taggable_type - string
class Post extends Eloquent {
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
class Video extends Eloquent {
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
class Tag extends Eloquent {
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
}
The seeder:
use Illuminate\Database\Seeder;
use App\Post;
use App\Tag;
class PostTableSeeder extends Seeder {
public function run() {
// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();
foreach ((range(1, 20)) as $index) {
$post = Post::create([
'name' => $faker->unique()->name
]);
// Do what here? $post->tags
}
}
}
Level 52
Something like that :
public function run() {
// use the factory to create a Faker\Generator instance
$faker = Faker\Factory::create();
foreach ((range(1, 20)) as $index) {
$post = Post::create([
'name' => $faker->unique()->name
]);
$post = Video::create([
'name' => $faker->unique()->name
]);
$post = Tag::create([
'name' => $faker->unique()->name
]);
}
foreach ((range(1, 20)) as $index) {
DB::table('taggables')->insert(
[
'tag_id' => rand(1, 20),
'taggable_id' => rand(1, 20),
'taggable_type' => rand(0, 1) == 1 ? 'App\Post' : 'App\Video'
]
);
}
}
4 likes
Please or to participate in this conversation.