Problem to iterate in 2 tables with has_many relationship

I have 2 tables.

Galeria has_many foto (or in english: an album has many photos)

// This don't work and gives me error.

foreach($galeria->fotos as $foto)


    echo 'foto:' . $foto->imagem;


Indirect modification of overloaded property Galeria::$fotos has no effect

// This works.

$total =  count($galeria->fotos);

for ($i=0; $i < $total; $i++)


    echo $galeria->fotos[$i]->titulo;


Can someone explains me why iteration with foreach statement doesn't work?

Is this some issue by Yii framework or a bug?

Sorry, but this problem is very strange to me.

From a performance point of view I wouldn't really do it this way. Just getting a dump of images data with a gallery could potentially be quite a heavy load on your system, what if your gallery has 10 thousand images for example, extreme but kind of makes the point.

Bets thing to do is just call the photos model and search by the galleryID.

$criteria = new CDbCriteria;

$criteria -> condition = "galleryID = :galleryID";

$criteria -> params = array(":galleryID" => $_GET['galleryID']);

$pages = new CPagination(Photos::model() -> count($criteria));

$pages -> pageSize = 30;

$pages -> applyLimit($criteria);

$photos = Photos::model() -> findAll($criteria);

This way your limiting the records to 30 per page, so your performance will be better then just dumping all the images out on the page.

Good point!

Really will load a massive content.

Wouldn't be possible to make a one gallery load one image? Like limit 1

I want this because I'd like to make a thumb pic in gallery and then when clicked will redirect to a page with all pics paginated.

I think so, take a look at the relations method for CActiveRecord:


Perhaps something like this:

public function relations() {

	return array(

		'photo' => array(self::HAS_ONE, 'Photos', 'galleryID', 'order' => 'RAND()')



I haven't tested that, but it might work lol. But yes what your asking should be possible, have a play.