CodeIgniter Forums
Delete cascade ? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Delete cascade ? (/showthread.php?tid=68222)



Delete cascade ? - tonny16 - 06-12-2017

Hello,
I have an article table and a comment table. I hope that the comments of the article also disappear, how to do?

Thank you in advance


RE: Delete cascade ? - skunkbad - 06-12-2017

Answer easily found:

http://lmgtfy.com/?q=mysql+on+delete+cascade


RE: Delete cascade ? - Paradinight - 06-12-2017

(06-12-2017, 04:42 AM)tonny16 Wrote: Hello,
I have an article table and a comment table. I hope that the comments of the article also disappear, how to do?

Thank you in advance

PHP Code:
$data = array(
   'deleted' => 1
);

$this->db->where('article_id'$article_id);
$this->db->update('article'$data); 

i prefer the soft delete. After x-months you can delete the rows.

If you use foreign keys you only need to delete the article (on delete cascade)

http://www.mysqltutorial.org/mysql-foreign-key/


if not: delete first the comments then the article

PHP Code:
$this->db->where('article_id'$article_id);
$status $this->db->delete('comments');
...
$this->db->where('article_id'$article_id);
$this->db->delete('article');
.... 



RE: Delete cascade ? - tonny16 - 06-14-2017

Thank you for your answers.

In mySQL I put this code:
PHP Code:
ALTER TABLE blog_commentaires
ADD CONSTRAINT fk_comments_article         
    FOREIGN KEY 
(id_article           
    REFERENCES article
(id)
 
   ON DELETE CASCADE


How to put it in Codeigniter?

Thank you in advance


RE: Delete cascade ? - rtenny - 06-15-2017

In CI you can run any SQL statement with the query function

$this->db->query("
ALTER TABLE blog_commentaires
ADD CONSTRAINT fk_comments_article
FOREIGN KEY (id_article)
REFERENCES article(id)
ON DELETE CASCADE;
");


RE: Delete cascade ? - rtenny - 06-15-2017

Its all in the manual and much quicker to find then waiting for a reply in the forum

https://www.codeigniter.com/user_guide/database/examples.html


RE: Delete cascade ? - tonny16 - 06-17-2017

(06-15-2017, 08:27 AM)rtenny Wrote: Its all in the manual and much quicker to find then waiting for a reply in the forum

https://www.codeigniter.com/user_guide/database/examples.html

Thanks for all, I used an other solution 
PHP Code:
$this->db->select('*');
        
$this->db->from('article');
        
$this->db->join('blog_commentaires''blog_commentaires.id_article = article.id');
        
$this->db->where('statut'"0");
        
$this->db->order_by('blog_commentaires.date''DESC');
        
        
$this->comments $this->db->get()->result();

        return 
$this->comments