allocatr/application/admin/model/BaseModel.php
2025-03-10 23:07:20 +08:00

58 lines
1.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\admin\model;
use think\Db;
use think\Exception;
use think\Model;
class BaseModel extends Model
{
/**
* 批量插入数据到数据库
*
* @param string $table 数据表名
* @param array $data 待插入的数据
* @param int $batchSize 每次插入的数据量(默认 500
* @return int 成功插入的总行数
* @throws Exception 插入失败时抛出异常
*/
function batchInsert( array $data, int $batchSize = 500): int
{
if (empty($data)) {
throw new Exception('插入数据不能为空');
}
// 提取字段名(确保所有数据的字段一致)
$columns = array_keys($data[0]);
$columnList = implode(', ', $columns);
$placeholders = '(' . implode(', ', array_fill(0, count($columns), '?')) . ')';
$totalInserted = 0;
Db::startTrans();
try {
// 数据分批插入
foreach (array_chunk($data, $batchSize) as $chunk) {
$sql = "INSERT INTO {$this->getTable()} ({$columnList}) VALUES " . implode(', ', array_fill(0, count($chunk), $placeholders));
// 将数据展开填充
$values = [];
foreach ($chunk as $row) {
$values = array_merge($values, array_values($row));
}
Db::execute($sql,$values);
}
Db::commit();
return $totalInserted;
} catch (Exception $e) {
Db::rollback();
throw new Exception('批量插入失败:' . $e->getMessage());
}
}
}