Join Models

I have 2 models (student and studentclass).

Student Model: student_id, student_name, student_gender

Student Class Model: student_id, class_id

In Student admin view, I want to filter records on the base of class dropdownlist. I have tried with following code but can’t succeed. Any other solution will be appreciated




public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		 'student_class'   => array(self::BELONGS_TO, 'ClassStudents', 'id'),

		);

	}


public function search()

	{

....

$criteria->with = array('student_class');

		$criteria->compare( 'student_class.student_id', $this->id, true );

		$criteria->together = true;


...

}



Javed Mian

give it a spin




<?php


public function relations()

{

        // NOTE: you may need to adjust the relation name and the related

        // class name for the relations automatically generated below.

        return array(

        	'student_class' => array(self::BELONGS_TO, 'ClassStudents', 'id'),

        );

}


public function search()

{

	....


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

	...

}




// change your gridview columns

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

	'id'=>'sale-grid',

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

	'filter'=>$model,

	'columns'=>array(

		...

		[

			'name'=>'class_id',

			'value'=>'$data->student_class->classname',

			'filter'=>CHtml::activeDropDownList($model, 'class_id', CHtml::listData(ClassStudents::model()->findAll(), 'id', 'classname') ),

			// NOTE: change "classname" to your column name

		],

		...

		array(

			'class'=>'CButtonColumn',

		),

	),

)); 


?>