1

我正在尝试为数据透视表创建 soem 播种机数据。下面的代码在某一点上会遇到重复错误。

有没有办法更好地做到这一点或改进此代码,以免造成重复。

 $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
      ];
 });

有错误 Integrity constraint violation: 1062 Duplicate entry

但在极少数情况下它会过去,但我想确保它一直都在。

这是在我的播种机类中运行的

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

谢谢

4

1 回答 1

0

我尝试制作一种递归方法来检查随机创建的 id。这对我有用;

$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);
于 2015-12-15T22:13:07.420 回答