如何在 Laravel 中使用伪造者播种随机 id 或 null?



我正在尝试用同一表的随机 id 播种parent_id列或让它为 null。

我认为它会起作用:

...
'parent_id' => $faker->boolean() ? Page::all()->random()->id : null,
...

但是我收到以下错误:

You requested 1 items, but there are only 0 items available. 

有谁知道如何做到这一点?

更新1:

使用伪动漫答案,我尝试了流动:

$factory->define(Page::class, function (FakerGenerator $faker) {
...
$parent_id = null;
...
$has_parent = $faker->boolean(50);
Log::debug('$has_parent' . $has_parent);
if ($has_parent) {
$parents = Page::all();
Log::debug('$parents' . count($parents));
if ($parents->isEmpty()) {
Log::debug('isEmpty');
$parent_id = null;
} else {
Log::debug('$parents->random()' . print_r($parents->random(), true));
$parent_id = $parents->random()->id;
}
}
return [
...
'parent_id' => $parent_id,
...
];
}

从我每次运行时看到的情况来看Page::all();返回空。 知道这是为什么吗?

试试这个:

'parent_id' => $faker->boolean(50) ? Page::orderByRaw('RAND()')->first()->id : null,

本质上,我们说的是,随机排序,获取第一个,然后获取它的 id。

boolean(50)应该给你50%的真几率,所以50%的假。

$factory->define(Page::class, function (FakerGenerator $faker) {
$ids = Page::pluck('id')->toArray();
return [
'parent_id' = empty($ids) ? null : $faker->optional(0.9, null)->randomElement($ids);  // 10% chance of null
];
});

给定"父"作为父模型,我这样做:

  1. 首先播种父母;
  2. 在工厂中使用以下代码为 Child 表设定种子:

'parent_id' => $faker->optional()->randomElement(AppParent::all()->pluck('id'))

它之所以有效,是因为 faker 的randomElement((采用一个数组,您可以使用父表的所有且仅填充">id">值填充该数组。

optional((faker 的修饰符会或不会随机在parent_id中放置 NULL。如 faker 的 GitHub 中所述,optional(( 有时会绕过提供程序来返回默认值(默认为 NULL(。您还可以指定接收默认值的概率和要返回的默认值。

注意:如果父表未设定种子,则无法执行任何操作。如果是这样,请考虑 dlnsk 的答案。

发生错误是因为您对页面(page:all((->random(((的查询未返回任何结果。

基本上,您的问题是,您关心在创建页面之前尝试为页面创建父级。

你可以尝试检查 Page::all(( 是否返回一个非空集合,如果是,那么从那里获取一个随机元素,如果没有,创建一个新元素。

我个人会做一些事情,比如为空父元素创建一个类,一个可以做空和非空父元素的类。

$factory->defineAs(Page::class, 'ParentPage', function (Faker $faker) {
return [
//the rest of your elements here
'parent_id' => null
];
});
$factory->defineAs(Page::class, 'page', function (Faker $faker) {
$has_parent = $faker->boolean();
if($has_parent) {
$parents = Page::all();
if($parents->isEmpty()) {
$parent_id = factory(Page::class, 'ParentPage')->create()->id;
} else {
$parent_id = $parents->random()->id;
}
}
return [
//the rest of your elements here
'parent_id' => $has_parent? $parent_id : null
];
});

您可以在播种机中创建常规页面,例如factory(Page::class, 'page')->times(50)->create();

上面的代码没有经过测试,但逻辑应该是正确的。

public function run()
{
factory(AppComment::class, 30)->make()->each(function ($comment){
$comments = Comment::all();
if ($comments->count() == 0) {
$comment->parent = null;
} else {
$rand = random_int(1, $comments->count());
if ($rand >= 2 && $rand <= 5){
$comment->parent = null;
}elseif ($rand >= 12 && $rand <=17){
$comment->parent = null;
}elseif ($rand >= 22 && $rand <= 27){
$comment->parent = null;
}else{
$comment->parent = $rand;
}
}
$comment->save();
});
}

最新更新