首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何划分由CodeIgniter的update_batch()和insert_batch()执行的数据行?

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

Stack Overflow用户
提问于 2020-05-30 09:31:03
回答 1查看 241关注 0票数 1

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

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

代码语言:javascript
复制
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将类似于以下内容:

代码语言:javascript
复制
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
    )
)

我的桌子结构是这样的:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-31 02:53:38

查询表中包含$dataSet.

  • Then中存在的sr_no值的预先存在的行,将键应用到来自sr_no值的结果集行--这允许根据旧数据快速查找新数据(查看各自的新行是否应该插入、作为更新执行,还是由于数据相同而完全被忽略。)

未经检验的建议:

代码语言:javascript
复制
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');
    }
}

附注:如果您的业务逻辑要求sr_no值是唯一的,我建议您将sr_no列设置为唯一键,从而在表配置中反映这一点。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62100515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档