Laravel 8 times() {#collection-method}
2021-07-19 09:49 更新
静态 times
方法通过调用给定次数的回调函数来创建新集合:
$collection = Collection::times(10, function ($number) {
return $number * 9;
});
$collection->all();
// [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
使用这个方法可以与工厂结合使用创建出 Eloquent 模型:
$categories = Collection::times(3, function ($number) {
return Category::factory()->create(['name' => "Category No. $number"]);
});
$categories->all();
/*
[
['id' => 1, 'name' => 'Category No. 1'],
['id' => 2, 'name' => 'Category No. 2'],
['id' => 3, 'name' => 'Category No. 3'],
]
*/
以上内容是否对您有帮助:
更多建议: