【问题标题】:Laravel - how to update whole collectionLaravel - 如何更新整个集合
【发布时间】:2015-04-21 22:38:56
【问题描述】:

我正在尝试使用 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() 更新它们。这是唯一的方法吗?

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

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

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

    【讨论】:

    • 不错!还没有听说过modelKeys-method。稍后会尝试。谢谢!
    • 完美运行。再次感谢! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多