我正在使用相关的模型列与CGridView过滤作斗争,我有两个模型Cars和Color,因此Color has_many Car and Car belongs_to 颜色。相关模型的网格列显示正常,我只是无法用它过滤。我收到mysql错误
Column not found: 1054 Unknown column 'carName'
颜色模型 HAS_MANY - 汽车
我从Car模型中声明了变量$ carName,因此该模型可以看到它。
public $carName;
public function rules()
{
return array(
array('id, carName, colourName', 'safe', 'on'=>'search'),
)
}
public function relations()
{
return array(
'CarsObj'=>array(self::HAS_MANY, 'Cars', 'colourID')
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->with = "CarsObj";
$criteria->compare('carName', $this->carName, true);
$criteria->compare('id',$this->id);
$criteria->compare('colourName',$this->colourName,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
汽车模型 BELONGS_TO - 颜色
public function relations()
{
return array(
'ColourObj'=>array(self::BELONGS_TO, 'Colour', 'colourID')
);
}
CGridView,我使用颜色模型搜索作为我的dataProvider
$model = new Colour('search');
$data = $model->search();
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$data
,'filter'=>$model
,'pager'=>array('header'=>'')
,'columns'=>array( //related model column
'id',
'colourName',
array(
'header' => 'carName',
'type' => 'raw',
'name' => 'carName',
'value' => function($data, $row) { //$data is item of DataProvider, $row is number of row (starts from 0)
$carNames= CHtml::listData((array)$data->ColourObj, 'id', 'carName');
return implode(', ', $carNames);
}
)
答案 0 :(得分:0)
默认情况下,CActiveRecord使用延迟加载。您需要将属性together设置为true。使用with
时,设置表别名也是一种很好的做法。
public function search(){
$criteria=new CDbCriteria;
$criteria->together = true;
$criteria->with = 'CarsObj';
$criteria->compare('CarsObj.carName',$this->carName,true);
$criteria->compare('t.id',$this->id);
$criteria->compare('t.colourName',$this->colourName,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}