Hy guys!
I would just like to find out if there is an easy way to avoid duplication's when seeding a pivot table.
I have these two tables:
category
post
and a pivot table:
category_post
I can seed them, and it works, my relations are working two.
Everything works, except the fact that i have posts that belong to multiple categories.
So i want a post to belong to only one categore, categories of course have more posts.
This is how my category_post_seed file looks like:
class CategoryPostTableSeeder extends Seeder {
public function run()
{
$faker = Faker::create();
$categoryIds = Category::lists('id');
$postIds = Post::lists('id');
foreach(range(1, 50) as $index)
{
DB::table('category_post')->insert([
'category_id' => $faker->randomElement($categoryIds),
'post_id' => $faker->randomElement($postIds)
]);
}
}
}
Thanks for any help.
Category
has manyPost
, andPost
belongs toCategory
. Then there is a foreign key on theposts
table that links to the primary key of thecategories
table, thus you won't be able to make onePost
belong to manyCategory
, which you have now. – Jarek Tkaczyk