1 回答

TA貢獻1859條經驗 獲得超6個贊
在您的表中查詢包含
sr_no
您的$dataSet
.然后將鍵應用于值中的結果集行
sr_no
——這允許根據舊數據快速查找新數據(以查看是否應插入相應的新行、作為更新執行或完全忽略,因為數據是相同的。
未經測試的建議:
function insertUpdateMacroPlan($dataSet)
{
$keyedExistingRows = array_column(
$this->db
->where_in('sr_no', array_column($dataSet, 'sr_no'))
->get('macro_plan')
->result_array(),
null,
'sr_no'
);
foreach ($dataSet as $data) {
if (isset($keyedExistingRows[$data['sr_no']])) {
// sr_no exists in the db, add known id to new data array
$identified = ['id' => $keyedExistingRows[$data['sr_no']]['id']] + $data;
if ($identified != $keyedExistingRows[$data['sr_no']]) {
$updateBatch[] = $identified;
}
// if the arrays contain the same data, the new data will be discarded
} else {
$insertBatch[] = $data;
}
}
if (!empty($insertBatch)) {
$this->db->insert_batch('macro_plan', $insertBatch);
}
if (!empty($updateBatch)) {
$this->db->update_batch('macro_plan', $updateBatch, 'id');
}
}
ps 如果您的業務邏輯要求sr_no值是唯一的,我建議您通過將sr_no列設置為唯一鍵來反映在您的表配置中。
- 1 回答
- 0 關注
- 154 瀏覽
添加回答
舉報