Active Record Issue With Relations

Hey Guys,

I’ve run into an issue with relations. I have to models with relations:

GGame:




/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'thumbnail'=>array(self::HAS_MANY, 'GPictures', 'game_id',

				'condition'=>"thumbnail.name='thumbnail'",

			)

		);

	}






and GPictures:





/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'game'=>array(self::BELONGS_TO, 'GGame', 'game_id')

		);

	}




now I do a query on GGame like this:





$criteria = new CDbCriteria;

		$criteria->limit = 10;

		$criteria->order = 'id DESC';

		

		$items = GGame::model()->with('thumbnail')->findAll($criteria);




if I do a dump: <?php echo "<pre>"; var_dump($items[4]->thumbnail); echo "</pre>";?>

I can see that the model is loaded together with the thumbnail image:

["_new":"CActiveRecord":private]=>

bool(false)


[&quot;_attributes&quot;:&quot;CActiveRecord&quot;:private]=&gt;


array(4) {


  [&quot;id&quot;]=&gt;


  string(2) &quot;15&quot;


  [&quot;name&quot;]=&gt;


  string(9) &quot;thumbnail&quot;


  [&quot;type&quot;]=&gt;


  string(4) &quot;.jpg&quot;


  [&quot;game_id&quot;]=&gt;


  string(2) &quot;16&quot;


}

but if I print out: <?php echo "<pre>"; var_dump($items[4]->thumbnail->name); echo "</pre>";?>

or any other field from the GPictures table it always is set to NULL.

Anyone got an idea what I am doing wrong here?

Any help is appreciated!

Thanks in advance!

Seb

You’ve set up a HAS_MANY relationship, so $item->thumbnail is actually an array. You might be better off renaming that relation as thumbnails and then accessing individual thumbnails by array index, such as




if (count($item->thumbnails))

    echo $item->thumbnails[0]->name;



If there’s only one thumbnail per game, you should set it up with a BELONGS_TO or HAS_ONE relationship.

ah I see, thanks a lot Keith!