Relational Queries Confusion

I am slightly confused with relational queries. Could somebody help me with this example. I have 2 tables City and State

State table has

id (PK)

name varchar(128)

City table has

id (PK)

name

stateid (fK)

Now I want to use a relational query that displays the name field of both the city and state by using findByPk (Primary key of city table). For example, the output should be Houston (city name), Texas (state name).


$city = City::model()->with('state')->findByPk($id);

echo $city->name . ' ' . $city->state->name;

Make sure you have set relation ‘state’ in City model.

if you create table both with the engine of InnoDB, it means that fk is supported, then gii will generate the relation between these two tables for you automatically.

if not, you have to wirte the relations by yourself. that is:




//in State Model

public function relations()

	{

		return array(

			'citys' => array(self::HAS_MANY, 'City', 'stateid'),

		);

	}


//in City Model

public function relations()

	{

		return array(

			'state' => array(self::BELONGS_TO, 'State', 'id'),

		);

	}



Now, you can get relational citys in state model, and get relational state in city model. That is:




$city=City::model()->findbyPk(id);

$state=$city->state;    //the state model you need