1

I ma trying to create soem seeder data for a pivot table. The code below works to one point that it will hit a duplication error.

Is there a way to do this better or to improve this code so not to cause duplication.

 $factory->define(Namespacehere\PostTag::class, function ($faker){

    $postsId =  $faker->randomElement(Namespacehere\Post::lists('id')->toArray());
    $tagsId =  $faker->randomElement(Namespacehere\Tag::lists('id')->toArray());

      return [
         'post_id' => $postsId,
         'tag_id' => $tagsId
      ];
 });

There error is Integrity constraint violation: 1062 Duplicate entry

But on the rare occasion it passes, but i want to make sure it does all the time.

This is run with in my seeder class

  public function run()
      {
          Namespacehere\PostTag::truncate();
          factory(Namespacehere\PostTag::class, 30)->create();
      }

Thanks

Simon Davies
  • 3,668
  • 9
  • 41
  • 69

1 Answers1

0

I've try to make a recursive method for checking random created ids. It's work for me;

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->sentence(mt_rand(3, 10)),
        'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))),
        'published_at' => $faker->dateTimeBetween('-1 month', '+3 days'),
    ];
});

$factory->define(App\Tags::class, function ($faker) {
    return [
        'title' => $faker->sentence(mt_rand(1, 3)),
    ];
});


$PostTagFactory = function ($faker) use (&$PostTagFactory) {

    $ids = [
        'post_id' => $faker->randomElement(App\Post::lists('id')->toArray()),
        'tag_id' => $faker->randomElement(App\Tags::lists('id')->toArray())
    ];

    if (App\PostTag::where('post_id', $ids['post_id'])->where('tag_id', $ids['tag_id'])->first() == null) {
        return $ids;
    } else {
        return $PostTagFactory();
    }

};

$factory->define(App\PostTag::class, $PostTagFactory);