您好,登錄后才能下訂單哦!
這篇文章主要介紹laravel怎么批量更新多條記錄,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
示例
<?php namespace App\Models; use DB; use Illuminate\Database\Eloquent\Model; /** * 學(xué)生表模型 */ class Students extends Model { protected $table = 'students'; //批量更新 public function updateBatch($multipleData = []) { try { if (empty($multipleData)) { throw new \Exception("數(shù)據(jù)不能為空"); } $tableName = DB::getTablePrefix() . $this->getTable(); // 表名 $firstRow = current($multipleData); $updateColumn = array_keys($firstRow); // 默認(rèn)以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 . ")"; // 傳入預(yù)處理sql語句和對應(yīng)綁定數(shù)據(jù) return DB::update($updateSql, $bindings); } catch (\Exception $e) { return false; } } }
可以根據(jù)自己的需求再做調(diào)整,下面是用法實(shí)例:
// 要批量更新的數(shù)組 $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)
以上是“l(fā)aravel怎么批量更新多條記錄”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。