我使用创建的集合在Laravel:
use Illuminate\Database\Eloquent\Collection; // As per Mihir Bhende's answer, make sure we're using the correct Eloquent `Collection`
$collection = new Collection;
然后我继续多个项目(所有相同型号的)推入该集合:
$item = $items->first(function($item) {
return $item->field == "value";
});
$collection->push($item);
最后,我试图用$collection
或$collection->update()
更新所有的,现在都在$collection->save()
的记录,但我收到了如下错误:
“法照亮的\ Support \收藏::更新不存在。”
但自从我使用new Collection
(和我也试了collect()
),和我打电话update()
非静态,我没想到这个错误。
我如何更新$collection
我的数据库中的记录都在一次?另外,有一种方法来“排队”起来就不会牺牲性能多个不同的子对象的变化?
谢谢!
您可以使用交易为“排队”的更新模型,并确保原子更新。
DB::transaction (function () use ($collection) {
$collection->each(function ($item) {
$item->save();
});
});
当然,最好的办法就是在交易关闭内做你的逻辑,这样你就不会需要循环他们多次:
DB::transaction(function () {
$items->each(function ($item) {
$item->field = "value";
$item->save();
});
});
这样,你就不需要循环回收多次了。
查看交易Laravel文档:https://laravel.com/docs/5.6/database#database-transactions
当您使用收集([]),它创造Illuminate\Support\Collection
其中作为雄辩模型,我们可以使用数据库更新功能是Illuminate\Database\Eloquent\Collection
您可以使用型号::水合物($数组)的数组转换为雄辩集合。
但是,在你的情况,如果你想保存的多条记录,看Model::create()
或Model::update()
。硒documentation