HAS_MANY relation and delete

Here is a relation in my Enquiry model:


'quotes'=>array(self::HAS_MANY, 'Quote', 'enquiry_id'),

In my EnquiryController if I have the following:


$model=Enquiry::model()->with('quotes')->findByPk($_GET['id']);


$model->delete();

  1. Am I right in assuming this would also delete the related records in Quote model? If not then how do I do this?

  2. How can I add a condition that ‘extends’ from the relation? So for example I need a condition that checks ‘accepted=1’ and a condition that checks ‘approved=1’.

No except if your database would support something like Cascade delete… else do it manual… The easiest way is generate a model for te join table and do a ModelHasStuff::model()->deleteAllByAttributes(array(‘model_id’ => $model->id));

On beforeDelete in the model

I’m just using a normal MySQL database. Would this not work:


$model=Enquiry::model()->with('quotes')->findByPk($_GET['id']);


$model->quotes->delete();


$model->delete();

Sorry I’m unable to test this at the moment so would appreciate any assistance :)

Umm oops sorry I thought you meant MANY_MANY x_x should learn how to read ;)

Mysql InnoDB has support for this… else do something like

Am not sure if with works u should have to test it but i think Yii does not delete relationships automatic ;) else just use Quotes::model()->deleteAllByAttributes(array(‘other_id’ =>$this->id));

Anyone got any other suggestions?

$model->quotes is an array (because the relation is HAS_MANY)

so you need





foreach($model->quotes as $quote)

   $quote->delete();




Also note when using Quotes::model()->deleteAllByAttributes(array(‘other_id’ =>$this->id)); callbacks are not triggered e.g. any code in beforeDelete/afterDelete…

But this should do many queries instead of 1… let’s say you have 1 user with 1000 articles :P doing 1000 queries instead of 1 ^^

yep!

but:

is just another suggestion!

I just tested and this does not work.

Late answer but if your sql doesn’t support cascading delete or you have another restrictions then:




$ids = array();

foreach($model->quotes as $quote) {

   $ids[] = $quote->id;

}

Quote::model()->deleteAll(array('condition' => 'id = :ids', 'params'=> array(':ids' => implode(',', $ids))));



I think if relation is there, you have a reference point already:




Quote::model()->deleteAllByAttributes(array('quote_parent_id' => $model->id));



Very late answer but here my 2 pence worth, This would also work if you found multiple parent results


		

$models = Models::model()->findByAttributes(array('id'=>$_GET['id']);

foreach($models as $model)

{

   $modelsId[] = $model->id;		

}

$criteria = new CDbCriteria;

$criteria->addInCondition('model_id',$modelsId);

Quotes::model()->deleteAll($criteria);