gpt4 book ai didi

php - Laravel - 如何更新整个集合

转载 作者:行者123 更新时间:2023-11-29 06:27:56 24 4
gpt4 key购买 nike

我正在尝试用 laravel 制作一个通知系统。我的想法是获取数据并立即更新“is_delivered”标志。

这是代码:

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 在更新时只支持限制(没有偏移量)。

但是如何在不循环遍历的情况下更新整个集合呢?循环即时更新会导致许多查询。我能想到的另一种方法是创建一个带有 ID 的数组并使用 whereIn() 更新它们。这是唯一的方法吗?

最佳答案

您可以对整个集合运行更新:

DB::table('table_name')->whereIn('id', $collection->modelKeys())->update(['is_delivered' => 1]);

关于php - Laravel - 如何更新整个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29784435/

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