亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何劃分要由 CodeIgniter 的 update_batch() 和 insert_batch

如何劃分要由 CodeIgniter 的 update_batch() 和 insert_batch

PHP
忽然笑 2023-04-21 16:34:26
我的目標是使用 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    ))我的表結構如下所示:
查看完整描述

1 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

  1. 在您的表中查詢包含sr_no您的$dataSet.

  2. 然后將鍵應用于值中的結果集行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列設置為唯一鍵來反映在您的表配置中。


查看完整回答
反對 回復 2023-04-21
  • 1 回答
  • 0 關注
  • 154 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號