我正在使用insert_batch()
函数将数据插入数据库。
我想分开处理。我的意思是,如果我想创建10000个序列号。但是一次1000行,它应该在一个循环中运行创建过程10次。
我该怎么做?
$serial_numbers = $this->serial_numbers_model->generate_serial_numbers($product_id, $partner_id, $serial_number_quantity, $serial_number_start);
$issued_date = date("Y-m-d H:i:s");
$inserted_rows = 0;
foreach ($serial_numbers as $sn) {
$check_number = $this->serial_numbers_model->generate_check_number();
$first_serial_number = reset($serial_numbers);
$last_serial_number = end($serial_numbers);
$inserted_rows++;
$insert_data[] = array(
'partner_id' => $partner_id,
'product_id' => $product_id,
'check_number' => $check_number,
'serial_number' => $sn,
'issued_time' => $issued_date,
'serial_number_status' => CREATE_STATUS
);
}
$this->serial_numbers_model->insert_batch($insert_data);
}
您的serial_numbers_model->insert_batch()
可能只是Codeigniter的原生insert_batch()
的包装?为了清楚起见,下面的代码使用了本机代码,根据需要将其替换为您的代码。
// Track how many in your batch, and prepare empty batch array
$count = 0;
$insert_data = [];
foreach ($serial_numbers as $sn) {
// ... your code, prepare your data, etc ...
$count++;
$insert_data[] = array(
// ... your data ...
);
// Do you have a batch of 1000 ready?
if ($count === 1000) {
// Yes - insert it
$this->db->insert_batch('table', $insert_data);
// $this->serial_numbers_model->insert_batch($insert_data);
// Reset the count, and empty the batch, ready to start again
$count = 0;
$insert_data = [];
}
}
// Watch out! If there were 1001 serial numbers, the first 1000 were handled,
// but the last one hasn't been inserted!
if (sizeof($insert_data)) {
$this->db->insert_batch('table', $insert_data);
}