gpt4 book ai didi

php - Laravel foreaching 随机模型

转载 作者:行者123 更新时间:2023-12-04 02:32:40 24 4
gpt4 key购买 nike

我正在为 M:M 关系制作播种机,我想在 90% 的情况下将 1 Widget 附加到 WorkspaceItem,其他 5% 2,最后 5 % 3.

$widgets = Widget::all();
$workspaceItems = WorkspaceItem::all();

foreach ($workspaceItems as $workspaceItem) {
$numberBetween = $faker->numberBetween(0, 100);

if ($numberBetween > 95) {
$widgetsToSeed = $widgets->random(3);
} else if ($numberBetween > 90 && $numberBetween <= 95) {
$widgetsToSeed = $widgets->random(2);
} else {
$widgetsToSeed = $widgets->random();
}

foreach ($widgetsToSeed as $widget) {
$workspaceItem->widgets()->attach($widget->id, [...]);
}
}

注意:我不能使用sync(),因为我有数据透视表的额外属性。

如果我 dd($widgetsToSeed),我确实会得到随机小部件。但是一旦它进入循环并且我 dd($widget) 我就没有得到模型,只有 true。似乎是什么问题?

最佳答案

我认为你应该能够做到:

$workspaceItem->widgets()->saveMany($widgetsToSeed);

这样你甚至不需要最后一个 foreach 循环。要始终接收一个集合(即使只有一个元素),您还可以在最后一个 else 语句中添加 random(1)。通过一些小的简化,它可能看起来像这样:

foreach ($workspaceItems as $workspaceItem) {
$numberBetween = $faker->numberBetween(0, 100);

if ($numberBetween > 95) {
$widgetsToSeed = $widgets->random(3);
} else if ($numberBetween > 90) {
$widgetsToSeed = $widgets->random(2);
} else {
$widgetsToSeed = $widgets->random(1);
}

$workspaceItem->widgets()->saveMany($widgetsToSeed);
}

关于php - Laravel foreaching 随机模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63227541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com