laravel分享一个根据主键进行批量更新的方法
有时候很需要一个能够实现批量更新的方法,但是laravel没有提供这样的实现,所以自己弄了一个,还是可以用的。
/** * 根据Id批量更新数据,可以放在model里面,使得每个model都是调用这个方法 * @author yezi * @param array $multipleData * @return bool */ public static function updateBatch($multipleData = array()) { $tableName = \DB::getTablePrefix() . app(Contract::class)->getTable(); if(!is_array($multipleData)){ throw new CustomValidationException('must be an array',null,'6001'); } foreach ($multipleData as &$row){ if(!array_key_exists('id',$row)){ throw new CustomValidationException('参数错误,缺少主键',null,'6001'); } $row[Model::FIELD_UPDATED_AT] = Carbon::now(); } if ($tableName && !empty($multipleData)) { $updateColumn = array_keys($multipleData[0]); $referenceColumn = $updateColumn[0]; unset($updateColumn[0]); $whereIn = ""; $q = "UPDATE " . $tableName . " SET "; foreach ($updateColumn as $uColumn) { $q .= $uColumn . " = CASE "; foreach ($multipleData as $data) { $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' "; } $q .= "ELSE " . $uColumn . " END, "; } foreach ($multipleData as $data) { $whereIn .= "'" . $data[$referenceColumn] . "', "; } $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")"; return \DB::update(\DB::raw($q)); } else { return false; } }