Model relations: joining models through foreign key in a related model

Hi guys,

I’ve been playing around with Yii for a week now and I am very impressed so far.

I have a question regarding model relations:

I have an Address model, which consists of a Suburb, State, Country.

Suburb is related to State, suburb.state_id = state.state_id.

State is related to Country, state.country_id = country.country_id.

When I do the following query I get the correct result, a Suburb model object with a State model object relation.

I understand that the Suburb model is not directly related to the Country model, is there a way I can link them so that I can access the Country model through the Suburb model.

$criteria = new CDbCriteria;

            $criteria->select = "suburb.suburb_id, suburb.suburb_name, suburb.postcode, suburb.state_id, state.state_name_full, state.country_id, country.country_name_full";

            $criteria->alias = 'suburb';

            $criteria->join = "INNER JOIN state ON suburb.state_id = state.state_id ";

            $criteria->join .= "INNER JOIN country ON state.country_id = country.country_id";

            $criteria->condition = "suburb.suburb_name LIKE ':sterm%'";

            $criteria->params = array(":sterm"=>$suburb);

            $criteria->order = "suburb.postcode";

            $suburbArray = Suburb::model()->findAll($criteria);

The SQL generated returns the desired columns when executed as plain sql, but because of the Model relations, the object returned does not include the Country columns as the Suburb-Country relation is not specified.

How can I achieve the desired model relation?

Thanks in advance.

I have just realised that I can do this:

($model is a Suburb model)


foreach($suburbArray as $model) {

                $arr[] = array(





Is this practice correct? What is it called, which topic does it come under so that I can read up more on it?

Also, should I do something like this in the Suburb model relation:

'country' => array(State::BELONGS_TO, 'Country', 'country_id')

Let me know if I should post more code to explain it better.


That is the way to use relational active records. Go here to learn more.