我试图为数据透视表创建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();
}
由于
答案 0 :(得分: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);