在Laravel中雄辩地使用UPDATE和ORDER BY

时间:2018-07-18 19:01:28

标签: sql laravel query-builder

我正在尝试根据给定的ID列表更新“ sortOrder”列。 例如,如果给定的ID为:

$orderList = ['id' =>'1','id' =>'5','id' =>'3']
ID of '1' => 'sortOrder column'  = 1
ID of '5' => 'sortOrder column'  = 2
ID of '3' => 'sortOrder column'  = 3

查询语句:

 $ids_array = array_pluck($orderList, 'id');
 $ids_string = implode(',', $ids_array);

 DB::statement(DB::raw('set @rownum=0'));

 $result = DB::table('requirements')
                 ->join('sections', 'sections.id', '=', 'requirements.section_id')
                 ->whereIn('id', $ids_array)
                 ->orderByRaw("FIELD(requirements.id, {$ids_string})")
                 ->update([
                     'requirements.sortOrder' => DB::raw('@rownum  := @rownum  + 1'),
                 ]);

但是当我尝试使用此查询进行更新时,出现错误:

SQLSTATE[HY000]: General error: 1221 Incorrect usage of UPDATE and ORDER BY

0 个答案:

没有答案