Removing rows from different tables in CodeIgniter

A bit of code snippet:

$this->db->where('id', $outfit_id);
$this->db->update('outfit_main',$data);

//Delete productsettings for specific outfit (They are added below with new values)
$this->db->where('outfit_id', $outfit_id);
$this->db->delete('outfit_products');

//Delete outfit_images for specific outfit as well. They are also added below
$this->db->where('outfit_id', $outfit_id);
$this->db->delete('outfit_images'); 

What I want to do:

  • Delete lines from outfit_main, where id = $ outfit_id
  • Remove rows from outfit_products, where outfit_id = $ outfit_id
  • Delete lines from outfit_images, where outfit_id = $ outfit_id

But actually, when I add the last two lines:

$this->db->where('outfit_id', $outfit_id);
$this->db->delete('outfit_images'); 

* removes all lines from outfit_main. why? *

+4
source share
4 answers

Try combining the where clause with the active delete entry:

$this->db->delete('outfit_main', array('id' => $outfit_id));
$this->db->delete('outfit_products', array('outfit_id' => $outfit_id));
$this->db->delete('outfit_images', array('outfit_id' => $outfit_id));
+6
source

, Ci old/cached where, , flush

$this->db->flush_cache();

$this->db->where('outfit_id', $outfit_id);
$this->db->delete('outfit_images');

, , . caching , , , .

+1

you can try this. but it will not work because. codeigniter ignore merge when deleting active records.

$this->db->join("table2", "table1.thing_id = table2.id")
  ->where("table2.otherthing_id", $id)
  ->delete("table1");

you can use the following code to delete data from different tables. This will help you.

$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));
+1
source

An array of table names can be passed to delete () if you want to delete data from more than one table. Much easier

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);
0
source

All Articles