简体   繁体   English

Codeigniter无法使用Join方法从数据库表中删除行

[英]Codeigniter cannot delete rows from database table using join method

I want to delete from 'table1' those rows where (user_id = 5) but I should check if those posts' (title = title1 in table2). 我想从“ table1”中删除其中的行(user_id = 5),但我应该检查是否有这些帖子”(title =表2中的title1)。 I use Codeigniter and I get this error while trying to delete: 'Deletes are not allowed unless they contain a "where" or "like" clause.' 我使用Codeigniter,尝试删除时收到此错误:“除非删除包含“ where”或“ like”子句,否则不允许删除。 Could you please help me to check what is wrong with my code below. 您能否帮助我检查下面的代码有什么问题。

table1: 表格1:

在此处输入图片说明

table2: 表2:

在此处输入图片说明

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;
    }

   } 

Make use of subqueries. 利用子查询。

example

#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'); 

References 参考

After running first query you will get the set of user that you have to delete. 运行第一个查询后,您将获得必须删除的用户集。 Run this set throw foreach loop for getting id of user and posts that you have to delete to an array. 运行此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;
  }

And then 接着

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

I know that this is not the best decision. 我知道这不是最好的决定。 But i think that this is the most understandable. 但是我认为这是最容易理解的。

You may use the following code to delete data from tables becasue codeigniter ignore join when you delete multiple data from multiple tables. 您可以使用以下代码从表中删除数据,因为当您从多个表中删除多个数据时,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));

如果要使用单个查询从多个表中删除数据,则JOINS用于从不用于删除数据的数据库中获取数据,那么您需要在MySQl中使用级联 ,从而可以从与当前表相关的其他表中删除数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM