簡體   English   中英

如果Codeigniter不存在則插入

[英]Insert if not exists with Codeigniter

我遇到以下問題,例如,如果phone,sushi_service_id都具有active = 1的行,則嘗試將數據插入表中:

ID | Phone | sushi_service_id | active
---------------------------------------
1  | 455   | 1                | 1 (LEGAL)
3  | 455   | 1                | 0 (LEGAL)
4  | 455   | 1                | 0 (LEGAL)
5  | 455   | 1                | 1  (NOT LEGAL! HAS THE SAME PHONE+SUSHI_SERVICE_ID+ACTIVE=1)

這是我的codeigniter代碼:如何才能使其像上面所說的那樣工作?

public function add($service, $phone, $sushi_subscription_id, $answer_id, $affiliate_id, $ip, $query, $invite_type, $invite_msg_id)
{

    $this->db->set('service_id', $service->id);
    $this->db->set('sushi_service_id', $service->sushi_service_id);
    $this->db->set('phone', $phone);

    if ($sushi_subscription_id) {
        $this->db->set('sushi_subscription_id', $sushi_subscription_id);
    }

    $this->db->set('answer_id', $answer_id);
    if ($affiliate_id) {
        $this->db->set('affiliate_id', $affiliate_id);
    }

    $this->db->set('added', 'NOW()', FALSE);

    $this->db->set('active', 1);
    $this->db->set('ip', $ip);

    $this->db->set('query', $query);

    if ($invite_type) {
        $this->db->set('invite_type', $invite_type);
    }

    if ($invite_msg_id) {
        $this->db->set('invite_msg_id', $invite_msg_id);
    }

    return ($this->db->insert($this->_table_name)) ? $this->db->insert_id() : FALSE;
}

我只是select * from XX where active = 1 ,然后根據num_rows的結果進行插入查詢。

最簡單的方法是在帶有ON DUPLICATE KEY UPDATE查詢的單個INSERT中。

示例結構:

INSERT INTO table ... VALUES .... ON DUPLICATE KEY UPDATE 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM