0
votes

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.

1
Why would you want that if you have many-to-many relationship?Jarek Tkaczyk
@deczo i don't think i want/have many-to-man relationship, but i may be wrong. Could you elaborate? Right now i want one post to belong to only one category, but a category has a lot of posts. Is that many-to-man?Mr. Sam
Many-to-many is a relation that you define with pivot table usualy, so you can link many posts to many categories. Otherwise you need one-to-many relation, which is, in the context of Eloquent, Category has many Post, and Post belongs to Category. Then there is a foreign key on the posts table that links to the primary key of the categories table, thus you won't be able to make one Post belong to many Category, which you have now.Jarek Tkaczyk

1 Answers

3
votes

You can use sync() which will remove all the rows from the pivot table for a certain post/category and then add a row for each item in the array. In this case, you'd only give it one item.

$category = Category::find(1);
$category->posts()->sync(array($somePostID));

    $faker = Faker::create();

    $categoryIds = Category::lists('id');
    $postIds = Post::lists('id');

    foreach(range(1, 50) as $index)
    {
        $category = Category::find($faker->randomElement($categoryIds));
        $category->posts()->sync(array($faker->randomElement($postIDs)));
    }