thinkphp6 insertAll没有INSERT IGNORE

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);

其他的正常使用,要是有人使用出现问题,也请告诉我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值