delete a model and all other models linked to it

I have a model of car and model of carpics. In database table tbl_carpics link to tbl_car via car_id. When I delete an entry from car model, all carpics linked to it will still remain. Whats the easiest way to delete them (carpics entries) as well at the time I am delete a single car?

Note: that carpic just stores the name of a file(an image) and car_id, so I will also have to delete a file which is present on harddisk for each carpic entry that is deleted.

How would you go about this? You dont have to give me code, just tell me where I should lay out things if you have good idea about it. I’d appreciate any tips on how you do it. Thanks!

just setup the database relations at database level and set "on delete => cascade"

if you use mysql, you can do it via phpmyadmin

thanks I also decided to put delete code in




public function beforeDelete()


$carpics = Carpics::model()->findAll(array(

'condition'=>'car_id=:value',

'params'=>array(':value'=> $this->id)));

	

foreach($carpics as $carpic)

{

	delete code here $carpic->filename;

}




hi gustavo,

how to recognize that one record is linked to other record in other table, so that I can disabled the delete button to prevent it from cascading (automatic) deletion. I want to push the user to check other record first before he/she doing the deletion. This is in the ‘Manage’ GridView.

Any suggestion?

you can track the related record using the foreign key ( use the current record id ) of the related table and if you don’t want cascade deletion you should not use on delete cascade in related table.

you can track the related record using the foreign key ( use the current record id ) of the related table and if you don’t want cascade deletion you should not use on delete cascade in related table.