Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete action doesn't work with related models in Yii

I have these relations in two models (photo, album). In item model:

'photo' => array(self::HAS_MANY, 'photo', 'album_id')

In photo model:

'album' => array(self::BELONGS_TO, 'Album', 'album_id'),

And in actionDelete of albumController:

 $this->loadModel($id)->photo->delete();

But nothing happens and the album doesn't get deleted.

What is the problem?

like image 959
hd. Avatar asked Dec 19 '25 04:12

hd.


2 Answers

Album has many photos in your relation, you should delete them in a loop

$photos = $this->loadModel($id)->photo;
foreach($photos as $photo)
    $photo->delete();

Or you may delete them in one query:

Photo::model()->deleteAllByAttributes(array('album_id'=>$id))
like image 136
Alex Avatar answered Dec 20 '25 17:12

Alex


Since you have HAS_MANY relation, you'll have to delete many objects, so to make it happen using 1 call, you can do it through the other model, so in the Album model put this method:

public function deletePhotos() {    
    return Photo:::model()->deleteAllByAttributes(array('album_id' =>$this->id));
}
like image 25
Abed Hawa Avatar answered Dec 20 '25 19:12

Abed Hawa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!