雄辩的-更新集合中的所有模型 [英] Eloquent - Updating all models in a collection
问题描述
我想在集合的所有模型中设置一个特定的属性.
I want to set a certain attribute in all the models of a collection.
在普通SQL中:
UPDATE table SET att = 'foo' WHERE id in (1,2,3)
我拥有的代码:
$models = MyModel::findMany([1,2,3]);
$models->update(['att'=>'foo']);
摘自此处
但不起作用.我要
Call to undefined method Illuminate\Database\Eloquent\Collection::update()
我发现它是使用查询生成器构建查询的唯一方法,但我宁愿避免这种情况.
the only way i have found it's building a query with the query builder but i'd rather avoid that.
推荐答案
您正在返回一个集合,而不是使查询保持打开状态以进行更新.就像您的示例正在做的那样.
You are returning a collection, not keeping the query open to update. Like your example is doing.
$models = MyModel::whereIn('id',[1,2,3]);
$models->update(['att'=>'foo']);
whereIn
将在您的案例id
中查询一列,第二个参数是要返回的ID的数组,但不会执行查询.您正在使用的findMany
正在执行它,因此返回模型的集合.
whereIn
will query a column in your case id
, the second parameter is an array of the ids you want to return, but will not execute the query. The findMany
you were using was executing it thus returning a Collection of models.
如果需要让模型用于其他用途,可以执行$collection = $models->get();
,它将返回模型的集合.
If you need to get the model to use for something else you can do $collection = $models->get();
and it will return a collection of the models.
如果您不只是像这样简单地将其写在一行上;
If you do not just simply write it on one line like so;
MyModel::whereIn('id',[1,2,3])->update(['att'=>'foo']);
我不推荐的另一种选择是使用以下内容;
Another option which i do not recommend is using the following;
$models = MyModel::findMany([1,2,3]);
$models->each(function ($item){
$item->update(['att'=>'foo']);
});
这将循环遍历集合中的所有项目并分别进行更新.但我建议使用whereIn
方法.
This will loop over all the items in the collection and update them individually. But I recommend the whereIn
method.
这篇关于雄辩的-更新集合中的所有模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!