1、mysql5.7
2、thinkphp6.0.8
做excel导入数据到数据库的时候,加盟号字段设置了唯一索引,excel导入重复数据的时候系统直接报错而不返回数据。
mysql本身是有insert ignore的,但是thinkphp6里面我是没有找到有这个支持,网上搜索的也没有这个支持。
所以决定尝试改一下这一块的代码。
// 这是tp6自带的数据重复就更新掉的功能,我是借用了这个功能来进行传参
Db::name('数据表') -> replace() -> insertAll($data);
// replace这个方法在thinkphp6\vendor\topthink\think-orm\src\db\Query.php里面
// 原代码,原代码不能传递bool之外的数据,我把bool进行了删除,不然不能传递参数
public function replace(bool $replace = true)
{
$this->options['replace'] = $replace;
return $this;
}
// 修改后
public function replace($replace = true)
{
$this->options['replace'] = $replace;
return $this;
}
// 然后是thinkphp6\vendor\topthink\think-orm\src\db\builder\Mysql.php
// 找到insertAll方法
// 修改为
if(isset($options['replace'])){
if($options['replace']==='IGNORE'){
$replace_type='IGNORE';
}else{
$replace_type=$options['replace'];
}
}else{
$replace_type=$replace;
}
return str_replace(
['%INSERT%', '%EXTRA%', '%TABLE%', '%PARTITION%', '%FIELD%', '%DATA%', '%DUPLICATE%', '%COMMENT%'],
[
// 原代码
// $replace ? 'REPLACE' : 'INSERT',
// 这个东西只能写出来自己临时使用,后期可能需要优化才能正常使用
$replace_type ? ($replace_type === 'IGNORE' ? 'INSERT IGNORE' : 'REPLACE') : 'INSERT',
$this->parseExtra($query, $options['extra']),
$this->parseTable($query, $options['table']),
$this->parsePartition($query, $options['partition']),
implode(' , ', $fields),
implode(' , ', $values),
$this->parseDuplicate($query, $options['duplicate']),
$this->parseComment($query, $options['comment']),
],
$this->insertAllSql);
使用的时候
Db::name('数据表') -> replace('IGNORE') -> insertAll($data);
其他的正常使用,要是有人使用出现问题,也请告诉我