利用laravel怎么对多条记录进行更新?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
实现方法如下:
<?php namespace App\Models; use DB; use Illuminate\Database\Eloquent\Model; /** * 学生表模型 */ class Students extends Model { protected $table = 'students'; //批量更新 public function updateBatch($multipleData = []) { try { if (empty($multipleData)) { throw new \Exception("数据不能为空"); } $tableName = DB::getTablePrefix() . $this->getTable(); // 表名 $firstRow = current($multipleData); $updateColumn = array_keys($firstRow); // 默认以id为条件更新,如果没有ID则以第一个字段为条件 $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn); unset($updateColumn[0]); // 拼接sql语句 $updateSql = "UPDATE " . $tableName . " SET "; $sets = []; $bindings = []; foreach ($updateColumn as $uColumn) { $setSql = "`" . $uColumn . "` = CASE "; foreach ($multipleData as $data) { $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? "; $bindings[] = $data[$referenceColumn]; $bindings[] = $data[$uColumn]; } $setSql .= "ELSE `" . $uColumn . "` END "; $sets[] = $setSql; } $updateSql .= implode(', ', $sets); $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all(); $bindings = array_merge($bindings, $whereIn); $whereIn = rtrim(str_repeat('?,', count($whereIn)), ','); $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")"; // 传入预处理sql语句和对应绑定数据 return DB::update($updateSql, $bindings); } catch (\Exception $e) { return false; } } }
可以根据自己的需求再做调整,下面是用法实例:
// 要批量更新的数组 $students = [ ['id' => 1, 'name' => '张三', 'email' => 'zhansan@qq.com'], ['id' => 2, 'name' => '李四', 'email' => 'lisi@qq.com'], ]; // 批量更新 app(Students::class)->updateBatch($students);
生成的SQL语句如下:
UPDATE pre_students SET NAME = CASE WHEN id = 1 THEN '张三' WHEN id = 2 THEN '李四' ELSE NAME END, email = CASE WHEN id = 1 THEN 'zhansan@qq.com' WHEN id = 2 THEN 'lisi@qq.com' ELSE email END WHERE id IN (1, 2)
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。