Question

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?

Was it helpful?

Solution

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))

OTHER TIPS

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));
}

The best practice is usunig data base Relational model first of all it work's faster, second you don't need to write a lot of php code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top