我试图在一个 CGridView 界面中访问 2 个相关模型以搜索元素。但是,一旦我将第二个表加入第一个表,搜索就会停止工作并且不过滤任何内容(网格未更改)。我已经提到了很多链接,但我自己无法解决这个问题。
表是 - UserMaster (user_id, name, status, ...) CustomerMaster (customer_id, user_id, account_number,...)
usermaster model content -
public $account_number;
public function rules()
{
return array(
array('name', 'required'),
array('account_number', 'safe'),
array('user_id, name,status, account_number', 'safe', 'on'=>'search'),
);
}
public function relations()
{
return array('customer_master' => array(self::HAS_ONE, 'CustomerMaster', 'user_id'),);
}
public function attributeLabels()
{
return array(
'user_id' => 'User',
'name' => 'Name',
'status' => 'Status',
'account_number' => 'Account Number',
);
}
public function search()
{
$criteria=new CDbCriteria;
$criteria->alias = 't';
$criteria->compare('t.user_id',$this->user_id);
$criteria->compare('t.name',$this->name,true);
$criteria->compare('t.status',$this->status);
$criteria->with = 'customer_master';
$criteria->condition = 't.user_type=2';
$criteria->together = true;
$criteria->compare('customer_master.user_id',$this->user_id,true);
if ($this->account_number){
$criteria->compare('customer_master.account_number',$this->account_number,true);
}
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>25),
'sort'=>array(
'defaultOrder'=>'t.user_id DESC',
),
));
}
customermaster model content-
public function relations()
{
return array(
'user_id' => array(self::BELONGS_TO, 'UserMaster', 'user_id'),
);
}
usermaster controller code -
public function actionAdmin()
{
$model=new UserMaster('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['UserMaster']))
$model->attributes=$_GET['UserMaster'];
$this->render('admin',array(
'model'=>$model,
));
}
admin.php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'user-master-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
array (
'name' => 'customer_master.account_number',
'header' => 'Account Number',
'type' => 'raw',
'value'=>'$data->customer_master->account_number',
),
'name',
'status',
array(
'class'=>'CButtonColumn',
),
),
));
通过加入上述 2 个模型,我能够按预期获得网格视图,但搜索不适用于所有字段。
有人请帮我找出问题所在。我希望我已经清楚地解释了问题。
提前致谢。