如何划分要由CodeIgniter的update_batch()和insert_batch()执行的数据的传入行?

问题描述 投票:0回答:1

我的目标是结合使用CodeIgniter的insert_batch()update_batch()将传入数据添加到我的macro_plan表中。

在下面的脚本中,我尝试基于sr_no值在数据库中查询现有行,然后适当地调用批处理查询方法。

function insert_batch($dataSet)
{
    $query = $this->db->query("select sr_no from macro_plan");
    $data = $query->result_array();
    $sr_nos=array();

    foreach($data as $key => $value):
        $sr_nos[$key]=$value['sr_no'];
    endforeach;

    $query1= $this->db->query("select * from macro_plan WHERE sr_no IN ('".$sr_nos."')");
    $update_query = $query1->result();
    if ($update_query->num_rows() > 0) {

        $this->db->update_batch($dataSet,$this->macro_plan);//update if ids exist
    } else {
        $this->db->insert_batch($dataSet,$this->macro_plan);//insert if does not exist
    }
}

但是,我收到“数组到字符串转换”错误。

$dataset类似于此:

Array (
    [0] => Array (
        [quantity_update] => 88
        [sr_no] => 2020-11-1
        [batch] => Batch 2
        [quantity_date_update] => 05-May-20
        [inq_id] => 49
    )
    [1] => Array (
        [quantity_update] => 99
        [sr_no] => 2020-11-2
        [batch] => Batch 1
        [quantity_date_update] => 11-May-20
        [inq_id] => 49
    )
)

我的表结构如下:

enter image description here

php sql codeigniter activerecord batch-processing
1个回答
1
投票
查询表以获取包含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.s。如果您的业务逻辑要求sr_no值是唯一的,则建议您通过将sr_no列设置为唯一键在表配置中反映出来。

  • © www.soinside.com 2019 - 2024. All rights reserved.