Laravel-如何更新整个收藏 [英] Laravel - how to update whole collection
问题描述
我正在尝试使用laravel创建通知系统.我的想法是获取数据并立即更新"is_delivered"标志.
I'm trying to make a notification system with laravel. My idea was to get data and update instantly the "is_delivered" flag.
这是代码:
Model:
public function scopeGetForView($query)
{
$query->orderBy('created_at','DESC');
$return = $query->get();
if($return->count() > 0) {
$query->update(array("is_delivered" => 1));
}
return $return;
}
Controller:
$notifications = Auth::user()->notifications()->limit(10)->offset(10)->getForView();
好吧,没有偏移就可以正常工作,因为MySQL在更新时仅支持限制(无偏移).
Well, this would work fine without the offset because MySQL does only support limit (without offset) when updating.
但是如何在不循环的情况下更新整个集合?即时更新循环将导致许多查询.我可以想到的另一种方法是创建一个具有ID的数组,并使用whereIn()更新它们.这是唯一的方法吗?
But how can I update the whole collection without looping through it? Looping with instant updating would lead to many queries. The other way I can think of would be to create an array with IDs and update them with whereIn(). Is this the only way doing it?
推荐答案
您可以对整个集合进行更新:
You can run an update on the whole collection:
DB::table('table_name')->whereIn('id', $collection->modelKeys())->update(['is_delivered' => 1]);
这篇关于Laravel-如何更新整个收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!