文章前导
在使用 Laravel 框架时发现框架的模型无法支持批量创建数据和批量修改数据。于是乎就自己封装了一个批量添加和批量修改数据的方法。只需要封装一个基础模型,让该基础模型 extend Model(框架自带的模型),其他的模型继承你的基础模型即可,全局调用。
示例演示
函数封装
代码语言:javascript复制use IlluminateDatabaseEloquentModel;
class BaseModel extends Model
{
public $timestamps = true;
protected $dateFormat = 'U';
CONST CREATED_AT = 'create_time';
CONST UPDATED_AT = 'update_time';
/**
* 批量添加
* @param string $tableName 数据表名
* @param array $info 插入的数据
* @return bool
* @author kert
*/
public function batchInsert(string $tableName, array $info): bool
{
$timeArray = [
'create_time' => time(),
'update_time' => time(),
];
array_walk($info, function (&$value, $key, $timeArray) {
$value = array_merge($value, $timeArray);
}, $timeArray);
return DB::table($tableName)->insert($info);
}
/**
* 批量更新
* @param string $tableName 数据表名
* @param array $info 更新的数据
* @return int 受影响的行数
* @author kert
*/
public function batchUpdate(string $tableName, array $info)
{
try {
if (count($info) > 0) {
$firstRow = current($info);
$updateColumn = array_keys($firstRow);
$referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
unset($updateColumn[0]);
$updateSql = "UPDATE " . $tableName . " SET ";
$sets = [];
$bindings = [];
foreach ($updateColumn as $uColumn) {
$setSql = "`" . $uColumn . "` = CASE ";
foreach ($info as $data) {
$setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
$bindings[] = $data[$referenceColumn];
$bindings[] = $data[$uColumn];
}
$setSql .= "ELSE `" . $uColumn . "` END ";
$sets[] = $setSql;
}
$updateSql .= implode(', ', $sets);
$whereIn = collect($info)->pluck($referenceColumn)->values()->all();
$bindings = array_merge($bindings, $whereIn);
$whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
$updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
return DB::update($updateSql, $bindings);
}
return 0;
} catch (Exception $e) {
return $e->getMessage();
}
}
}
函数调用
代码语言:javascript复制use BaseModel;
clasee User extends BaseModel
{
protected $table = 'user';
public function insert(arry $info):bool
{
return $this->batchInsert((string)$this->getTable(), (array)$info);
}
public function update(array $info):bool
{
return $this->batchUpdate((string)$this->getTable(), (array)$info);
}
}
数据格式
代码语言:javascript复制// 批量添加数据格式
$addData = [
['name' => '张三', 'age' => 12, 'sex' => '男'],
['name' => '张三', 'age' => 12, 'sex' => '男'],
['name' => '张三', 'age' => 12, 'sex' => '男'],
['name' => '张三', 'age' => 12, 'sex' => '男'],
];
// 批量更新数据格式
$updateData = [
['id' => 1, name' => '张三', 'age' => 12, 'sex' => '男'],
['id' => 2, 'name' => '张三', 'age' => 12, 'sex' => '男'],
['id' => 3, 'name' => '张三', 'age' => 12, 'sex' => '男'],
['id' => 4, 'name' => '张三', 'age' => 12, 'sex' => '男'],
];