Search code examples
phpmysqlyiiyii-cmodel

Yii Return Attributes of Joined Models


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?


Solution

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