laravel批量更新多条记录

来源:转载

写在前面

熟悉laravel的童鞋都知道,laravel有批量一次性插入多条记录,却没有一次性按条件更新多条记录。

是否羡慕thinkphp的saveAll,是否羡慕ci的update_batch,但如此优雅的laravel怎么就没有类似的批量更新的方法呢?

高手在民间

Google了一下,发现stackoverflow( https://stackoverflow.com/questions/26133977/laravel-bulk-update )上已经有人写好了,顺便做了参考,结合laravel的Eloquent做了调整。

<?phpnamespace 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 "; foreach ($updateColumn as $uColumn) { $updateSql .= $uColumn . " = CASE "; foreach ($multipleData as $data) { $updateSql .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' "; } $updateSql .= "ELSE " . $uColumn . " END, "; } // 更新条件,以逗号分隔 $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all(); $whereIn = implode(',', $whereIn); $updateSql = rtrim($updateSql, ", ") . " WHERE " . $referenceColumn . " IN (" . $whereIn . ")"; return DB::update(DB::raw($updateSql)); } catch (/Exception $e) { return false; } }}

可以根据自己的需求再做调整,下面是用法实例:

// 要批量更新的数组$students = [ ['id' => 1, 'name' => '张三', 'email' => '[email protected]'], ['id' => 2, 'name' => '李四', 'email' => '[email protected]'],];// 批量更新app(Students::class)->updateBatch($students);

生成的SQL语句如下:

UPDATE pre_studentsSET NAME = CASEWHEN id = 1 THEN '张三'WHEN id = 2 THEN '李四'ELSE NAMEEND, email = CASEWHEN id = 1 THEN '[email protected]'WHEN id = 2 THEN '[email protected]'ELSE emailENDWHERE id IN (1, 2)

是不是效率又提高了一大截呢~

原文 http://www.tech1024.cn/original/2950.html

分享给朋友:
您可能感兴趣的文章:
随机阅读: