0

In Yii, I have media which is tied to a location; I have the relations set up as so:

public function relations() {

    return array(
        'users' => array(self::HAS_ONE, 'Users', array('id' => 'user_id')), 
        'locations' => array(self::HAS_ONE, 'Locations', array('id' => 'object_id'), 'together' => true, 'select' => '*')
    );
}

When I query, I use the 'with' statement to join the tables.

$models = Media::model()->with('lodcation') -> findAll($criteria);

And then I am putting the data into a json object and returning it as a CJSON response.

echo CJSON::encode($models);

The problem is the fields that are being returned are only from the parent model, which is Media, and not the joined model, Locations. My question is how can I display both the parent model and joined model results in Yii?

tereško
  • 58,060
  • 25
  • 98
  • 150
Devin Dixon
  • 11,553
  • 24
  • 86
  • 167
  • what does `var_dump($models[0]->locations);` return? (assuming `with('lodcation')` is a typo in your question and you mean `with('locations')` ;)) – Stu Mar 21 '13 at 18:02

2 Answers2

2

Your relationship

'locations' => array(self::HAS_ONE, 'Locations', array('id' => 'object_id'), 'together' => true, 'select' => '*')

Has the name 'locations', but when you try to use it in your query you refer to ->with('lodcation'), which is making the findAll method trying to eagerly load data from an unexisting relation. Changing your call to $models = Media::model()->with('locations') -> findAll($criteria); should correct this problem.

Maybe the relationship name you're using is making some noise here: 'locations' as a plural seems to be referring to an array of locations. Keeping this name in single 'location' should make the meaning of the self::HAS_ONE relationship clearer.

Snivs
  • 1,105
  • 11
  • 20
1

CJSON::encode() will always only use the direct the attributes from the parent model. You could try one of these extensions instead:

Michael Härtl
  • 8,428
  • 5
  • 35
  • 62