【问题标题】:Codeigniter cannot delete rows from database table using join methodCodeigniter 无法使用连接方法从数据库表中删除行
【发布时间】:2014-12-22 17:43:56
【问题描述】:

我想从‘table1’中删除那些 (user_id = 5) 的行,但我应该检查那些帖子’(title = table2 中的 title1)。我使用 Codeigniter,但在尝试删除时出现此错误:'不允许删除,除非它们包含“where”或“like”子句。'请您帮我检查一下我的代码有什么问题。

table1:

table2:

public function delete($title, $user_id){ 

    $this->db->select('table1.*');
    $this->db->from('table1','table2');   
    $this->db->where('table1.user_id', $user_id); 
    $this->db->where('table2.title', $title);
    $this->db->join('table2','table1.post_id=table2.post_id');

     $query = $this->db->get();   

        if ($query && $query->num_rows() > 0) {

    $this->db->delete('table1.*');
    $this->db->from('table1','table2');   
    $this->db->where('table1.user_id', $user_id); 
    $this->db->where('table2.title', $title);
    $this->db->join('table2','table1.post_id=table2.post_id');
    return true;
            } 
    else {
    return false;
    }

   } 

【问题讨论】:

标签: php mysql codeigniter join


【解决方案1】:

利用子查询。

示例

#Create where clause
$this->db->select('id');
$this->db->from('table2');
$this->db->where('table2.title', $title);
$where_clause = $this->db->get_compiled_select();

#Create main query
$this->db->where('table1.user_id', $user_id); 
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
$this->db->delete('table1'); 

参考文献

【讨论】:

  • 感谢您的回答。还有另一种方法吗?因为我在 Codeigniter 文档中没有找到 get_compiled_select() 方法。
【解决方案2】:

运行第一个查询后,您将获得必须删除的用户集。 运行这个 set throw foreach 循环以获取用户 ID 和您必须删除到数组的帖子。

  $user_array = array();
  $post_array = array();

  foreach($query->result() as $query) 
  {
      $user_array[$query->user_id] = $query->user_id;
      $post_user[$query->post_id] = $query->post_id;
  }

然后

  this->db->where_in('user_id', $user_array)->delete('table1');
  this->db->where_in('post_id', $post_array)->delete('table2');

我知道这不是最好的决定。但我认为这是最容易理解的。

【讨论】:

    【解决方案3】:

    您可以使用以下代码从表中删除数据,因为当您从多个表中删除多个数据时,codeigniter 会忽略连接。

    $sql = "DELETE t1 FROM table1 t1
      JOIN table2 t2 ON t1.thing_id = t2.id
      WHERE t2.otherthing_id = ?";
    $this->db->query($sql, array($id));
    

    【讨论】:

      【解决方案4】:

      JOINS 用于从数据库中获取数据,而不是用于删除数据,如果您想使用单个查询从多个表中删除数据,那么您需要在 MySQl 中使用 cascading,这样您也可以删除数据来自与当前表相关的其他表。

      【讨论】:

        猜你喜欢
        • 2014-05-15
        • 1970-01-01
        • 2016-07-01
        • 2023-04-06
        • 1970-01-01
        • 2019-06-09
        • 2015-09-30
        • 2018-05-16
        相关资源
        最近更新 更多