[英]Yii, relation model filter search
I am battling with CGridView filtering using the related model column, I have two models Cars and Colour, so Colour has_many Car and Car belongs_to Colour.我正在与使用相关模型列的 CGridView 过滤作斗争,我有两个模型 Cars 和 Colour,所以 Color has_many Car 和Carbelongs_to Colour。 The grid column from related model displays fine, I'm just not able to filter with it.
来自相关模型的网格列显示正常,我只是无法使用它进行过滤。 I am getting mysql error
我收到 mysql 错误
Column not found: 1054 Unknown column 'carName'
Colour model HAS_MANY - Cars颜色模型HAS_MANY - 汽车
I declaired the variable $carName from the Car model, so this model can see it.我从 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,
));
}
Car Model BELONGS_TO - Colour汽车模型BELONGS_TO - 颜色
public function relations()
{
return array(
'ColourObj'=>array(self::BELONGS_TO, 'Colour', 'colourID')
);
}
CGridView, i am using the Colour Model search as my dataProvider CGridView,我使用颜色模型搜索作为我的数据提供者
$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);
}
)
By default CActiveRecord using lazy load.默认情况下 CActiveRecord 使用延迟加载。 You need to set attribute together true.
你需要设置属性一起真实的。 Also it's a good practice to set table alias when you using
with
.此外,在使用
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,
));
}
Try this尝试这个
public function search() {公共功能搜索(){
$criteria=new CDbCriteria;
$criteria->with = "CarsObj";
$criteria->compare('CarsObj.carName', $this->carName, true);
$criteria->compare('id',$this->id);
$criteria->compare('colourName',$this->colourName,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.