CDbCriteria and JOIN

Hi, I have two tables:


Gallery (id_gal, name_gal, desc_gal)

Images (id_img, id_gal, file_img)

Each image is associated with gallery via "id_gal" foreign key.

When we create CRUD with GII, it creates an "admin" section that uses CGridView to display data in a grid. "search()" method of Model class is used to provide data to CGridView on the admin page.

My question is, how to modify the search() method of Images model class so that I get Gallery table attributes in CGridView dataprovider?

The search function of Images model class is given below:


public function search()

{

$criteria=new CDbCriteria;

$criteria->compare('id_img',$this->id_img);

$criteria->compare('id_gal',$this->id_gal);

$criteria->compare('file_img',$this->file_img);

}

I tried below but it does not get any gallery table attributes:


public function search()

{

$criteria=new CDbCriteria;

[b]$criteria->with = array('gallery');[/b]

$criteria->compare('id_img',$this->id_img);

$criteria->compare('id_gal',$this->id_gal);

$criteria->compare('file_img',$this->file_img);

}

Thanks

First, say to Images model that has a relation:


    public function relations() {

        return array(

            'gallery' => array(self::BELONGS_TO, 'Gallery', 'id_gal'),        );

    }

Then call this relation in CGridView in /protected/views/images/admin.php

(note gallery.name_gal column: you have already loaded the model and now you just need to get the model value in your CGridView)




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

	'id'=>'image-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'id_img',

		'file_img',

		'gallery.name_gal',

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>