如何划分将由codeigniter的update\u batch()和insert\u batch()执行的传入数据行?

2exbekwf  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(604)

我的目标是使用codeigniter的 insert_batch() 以及 update_batch() 将传入数据添加到我的 macro_plan table。
在下面的脚本中,我试图根据查询数据库中的现有行 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
    )
)

我的表结构如下所示:

tzcvj98z

tzcvj98z1#

查询表中包含 sr_no 存在于你生活中的价值观 $dataSet .
然后将键应用于 sr_no values——这允许快速查找新数据和旧数据(以查看是否应该插入相应的新行,作为更新执行,还是因为数据相同而完全忽略)。
未经测试的建议:

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

p、 如果你的业务逻辑需要的话 sr_no 值是唯一的,我建议您通过设置 sr_no 列作为唯一键。

相关问题