Question

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?

Was it helpful?

Solution 2

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

OTHER TIPS

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.

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