phpmysqlcodeigniterjoinsql-delete

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). I use Codeigniter and I get this error while trying to delete: ‘Deletes are not allowed unless they contain a "where" or "like" clause.’ Could you please help me to check what is wrong with my code below.

table1:

enter image description here

table2:

enter image description here

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

   } 

Solution

  • 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