我想在表中插入行,如下所示:

$this->db->update_batch($this->table_name, $update, 'image_id');

if ($this->db->affected_rows() === 0) {
    $this->db->insert_batch($this->table_name, $update);
}

但如果它存在,我不想做任何事。但是上面的代码插入了另一行,因为没有行受到影响
我想我可以做一个INSERT IGNORE INTO,但我更喜欢使用CodeIgniters upate_batch和INSERT_batch。
$update-变量类似于
$update = array(
   array('id' => 1, 'name' => 'Gustav'),
   array('id' => 2, 'name' => 'Peter'),
   array('id' => 3, 'name' => 'Lisa')
)

更新
从我得到的答案来看,我对自己想要的东西还不够清楚。(我觉得我还不够清楚我想要什么,所以这里是我最新的问题,我希望更清楚)
//This will insert Gustav, Peter and Lisa

$update = array(
   array('image_id' => 1, 'name' => 'Gustav'),
   array('image_id' => 2, 'name' => 'Peter'),
   array('image_id' => 3, 'name' => 'Lisa')
)
$this->db->insert_batch($update);


//If I do this it would insert Party Gustav, Peter and Lisa.
$update = array(
   array('image_id' => 1, 'name' => 'Party Gustav'),
   array('image_id' => 2, 'name' => 'Peter'),
   array('image_id' => 3, 'name' => 'Lisa')
)
$this->db->insert_batch($update);

//Above will create 6 rows

但我想发生的是
$update = array(
   array('image_id' => 1, 'name' => 'Gustav'),
   array('image_id' => 2, 'name' => 'Peter'),
   array('image_id' => 3, 'name' => 'Lisa')
)
$this->db->insert_batch($update);

$update = array(
   array('image_id' => 1, 'name' => 'Party Gustav'),
   array('image_id' => 2, 'name' => 'Peter'),
   array('image_id' => 3, 'name' => 'Lisa')
)


//Insert batch but when existing image_ids just change the name
//from Gustav to Party Gustav (in this case)
$this->db->insert_batch($update);

//Above will create 3 rows

我想它等于。

最佳答案

首先从表中选择所有图像id。

$data = $this->db->select(`image_id`)->get($this->table_name)->result_array();

在数组中列出图像id。
$image_ids=array();

foreach($data as $key => $value):

$image_ids[$key]=$value[`image_id`];

endforeach;

$update = array(
   array('image_id' => 1, 'name' => 'Party Gustav'),
   array('image_id' => 2, 'name' => 'Peter'),
   array('image_id' => 3, 'name' => 'Lisa')
)

检查IMAGE ID是否存在:
$update_query= $this->db->where_in(`image_ids`,$image_ids)
               ->get($this->table_name)->result();

if($update_query->num_rows() > 0):

  $this->db->update_batch($update,$this->table_name);//update if ids exist
else
   $this->db->insert_batch($update,$this->table_name);//insert if does not exist
endif;

关于php - 更新一行,但如果行在codeigniter中不存在,则插入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24049652/

10-09 20:10
查看更多