【问题标题】:Delete multiple rows in Codeigniter by multiple columns按多列删除 Codeigniter 中的多行
【发布时间】:2020-03-03 07:17:45
【问题描述】:

我有一个关联数组,比如:

array(3) {
  [0]=>
  array(2) {
    ["userId"]=>
    string(1) "10"
    ["customerId"]=>
    string(3) "1809"
  }
  [1]=>
  array(2) {
    ["userId"]=>
    string(1) "13"
    ["customerId"]=>
    string(3) "1094"
  }
  [2]=>
  array(2) {
    ["userId"]=>
    string(1) "45"
    ["customerId"]=>
    string(2) "210"
  }
}

我正在尝试从数据库中删除这些行,但找不到要运行的正确 Codeigniter 查询。

生成的查询应该是这样的:

DELETE FROM table
WHERE (userId,customer_id) IN ( (10,1809),(10,1809),(45,210) )

如果我试试这个

$this->db->where_in( '(userId, customer_id)', array( array(10,1809), array(10,1809), array(45,210) ));
$this->db->delete('table');
die(var_dump($this->db->last_query()));

我明白了,当然这是不正确的:

DELETE FROM `table`
WHERE (userId, customer_id) IN(Array, Array, Array)

【问题讨论】:

  • 该表是否有一个主键,您正在尝试从中删除记录?
  • 如果是,则尝试使用 IN 关键字和该表的主键删除记录。它会起作用的。
  • @BeingprabhU 这两个是主键:userId 和 customer_id
  • 主键组合是什么??

标签: php codeigniter


【解决方案1】:

将关联的数组值放入单个数组中,然后传递给查询

$assoicative_array = array(array(10,20,30));
    $ids=array();
    foreach($assoicative_array as $key =>$value ){
        $ids[]=$value;
    }
    $this->db->where_in('userId',$ids);
    $this->db->where_in('customer_id',$ids);
    $this->db->delete('table');
    die(var_dump($this->db->last_query()));

【讨论】:

  • 他可以检查 $ids = array_unique($ids);克服它
  • @BeingprabhU 我可以删除这些记录,它是- ON UPDATE NO ACTION ON DELETE NO ACTION
  • @BeingprabhU 是的,可能有多个记录具有相同的userId,但可能没有具有相同userId 和customer_id 的记录
【解决方案2】:

这是我尝试过的,它有效:

foreach ( $data as $row )
{
    $userIds[] = $row['userId'];
    $customerIds[] = $row['customerId'];
}

$this->db->where_in('userId', $userIds);
$this->db->where_in('customer_id', $customerIds);
$this->db->delete('table');

这会删除行并且生成的查询是:

DELETE FROM `table`
WHERE `userId` IN('10', '11', '54')
AND `customer_id` IN('1809', '1904', '201')

【讨论】:

  • @elango,请编辑您的答案以将值存储在不同的变量中。
猜你喜欢
  • 2016-11-27
  • 2015-05-29
  • 2021-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
相关资源
最近更新 更多