Active Record - JOIN two tables


I have two tables. The first table consists of:

The second table:

I have two models to correspond with these two tables. The model for the first table has the following relations set up:

public function relations()


	brand => array(self::BELONGS_TO, 'Brands', 'ID');


The model for the second table has this relation set up:

public function relations()


	cars => array(self::HAS_MANY, 'Cars', 'BrandID');


Now, when using Active Record I can get all the data back from the first table and print it. It obviously echoes the BrandID. However, I’d like to modify my Active Record statement so that it will print the Brand name instead of the ID.

This is the AR statement I am using right now:

//$brandId gets populated through $_GET.

$criteria=new CDbCriteria;




I know this is very basic but I am not very familiar with AR and am happy for any contribution :)

My overall goal is, since I am displaying this in a CGridView to display the Brand name instead of the BrandID. To display the cars in the grid I am using $model->search(); for the dataProvider. Where $model=new Cars('search).

How can I modify the CGridView to actually display the name of the brand?


Well basically it goes like this, provided that the $model is a Cars instance.

$this->widget('zii.widgets.grid.CGridView', array(











Further to CGridView documentation, you can also check this wiki in order to take it to the next level (just read and test by yourself): Searching and sorting by related model in CGridView

Thanks, this article helped a lot :)