Codeigniter CI3-insert_批处理上的捕获错误(唯一输入错误)
我有一个表,其单元格具有唯一索引(hashCheck)。是否可以使用insert_batch,捕获数据库中已存在的所有条目(重复项),将它们放入数组并插入新记录?这是我目前使用的代码:Codeigniter CI3-insert_批处理上的捕获错误(唯一输入错误),codeigniter,codeigniter-3,Codeigniter,Codeigniter 3,我有一个表,其单元格具有唯一索引(hashCheck)。是否可以使用insert_batch,捕获数据库中已存在的所有条目(重复项),将它们放入数组并插入新记录?这是我目前使用的代码: public function insertSerials($serials, $type) { $data = []; $now = date('Y-m-d H:i:s'); foreach ($serials as $serial):
public function insertSerials($serials, $type)
{
$data = [];
$now = date('Y-m-d H:i:s');
foreach ($serials as $serial):
$data[] = [
'serial' => $this->encryption->encrypt($serial),
'hashCheck' => hash('xxx', $serial),
'type' => $type,
'date_added' => $now,
];
endforeach;
try {
$this->db->insert_batch($this->_table_name, $data);
} catch (Exception $e) {
var_dump('<pre>', $e, '</pre>');
}
}
公共函数insertSerials($serials,$type)
{
$data=[];
$now=日期('Y-m-d H:i:s');
foreach($serials作为$serial):
$data[]=[
“串行”=>this->encryption->encryption($serial),
'hashCheck'=>hash('xxx',$serial),
'type'=>$type,
“date_added”=>现在$,
];
endforeach;
试一试{
$this->db->insert\u batch($this->\u table\u name,$data);
}捕获(例外$e){
var_dump(“$e”);
}
}
这是我能想到的实现你目标的唯一方法。也许不那么优雅,但应该有用
如果将
db->insert()
放入循环中,我会感觉很糟糕,除非insert\u batch()
最终会这样做。不会很有用,因为没有任何CodeIgniter数据库类或驱动程序会抛出任何异常。
public function insertSerials($serials, $type)
{
$data = [];
$pre_existing = [];
$now = date('Y-m-d H:i:s');
foreach($serials as $serial)
{
$data[] = [
'serial' => $this->encryption->encrypt($serial),
'hashCheck' => hash('xxx', $serial),
'type' => $type,
'date_added' => $now,
];
//test for existing hashCheck
$query = $this->db->get_where($this->_table_name,
array('hashCheck' => $data['hashCheck']));
if($query->num_rows() > 0)
{
$pre_existing[] = $data;
}
else
{
$this->db->insert($this->_table_name, $data);
}
}
}