简体   繁体   English

Laravel雄辩的更新记录,最小值

[英]Laravel eloquent update record with minimum value

I need to find the minimum "priority" value and then set it's value to another entry, in place using laravel eloquent. 我需要找到最小的“优先级”值,然后使用laravel雄辩地将其值设置为另一个条目。

Is there any way to do so or any best practice for it? 有没有办法做到这一点或有什么最佳实践?

What I have in mind : 我的想法:

Orders::where('user_id', '!=', $user_id)
 ->where('odm_id', $odm_id)
 ->whereExpired(0)
 ->min('priority')
 ->update(['priority' => 1]);

FYI: Above approach is giving an error and is not working. 仅供参考:以上方法给出了一个错误,并且不起作用。 The Error Message is : 错误消息是:

Call to a member function update() on string

The problem is that min will return a number and not an actual model. 问题是min将返回一个数字而不是实际模型。 If you want the actual model which has the min value you need to something like: 如果要使用具有最小值的实际模型,则需要执行以下操作:

Orders::where('user_id', '!=', $user_id)
        ->where('odm_id', $odm_id)
        ->wherePriority(function ($query) use ($user_id, $odm_id) {
        $query->from(\DB::raw('(SELECT * FROM orders) AS o'))
              ->selectRaw("MIN(`o`.`priority`)")                   
              ->where('o.odm_id', $odm_id)
              ->where('o.expired', 0);
        })->update(['priority' => 1]);

Note that this will update all records which have expired 0, odm_id equal to $odm_id and match the minimum value. 请注意,这将更新所有过期0, odm_id等于$odm_id并匹配最小值的记录。

Alternatively you can do: 或者,您可以执行以下操作:

$orders =Orders::where('user_id', '!=', $user_id)
        ->where('odm_id', $odm_id)
        ->wherePriority(function ($query) use ($user_id, $odm_id) {
        $query->from(\DB::raw('(SELECT * FROM orders) AS o'))
              ->selectRaw("MIN(`o`.`priority`)")                   
              ->where('o.odm_id', $odm_id)
              ->where('o.expired', 0);
        })->get();

  $orders->each(function ($order) {
       $order->priority = 1;
       $order->save();
  });

The second way has the disadvantage of doing 2 separate queries, one to get the data and one to update, however this has the advantage of triggering model events such as saving etc. 第二种方法的缺点是执行两个单独的查询,一个查询获取数据,一个进行更新,但这具有触发模型事件(如保存等)的优点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM