Php 如何在yii中将sql查询结果左连接到模型gridview中
这是代码Php 如何在yii中将sql查询结果左连接到模型gridview中,php,sql,gridview,yii,Php,Sql,Gridview,Yii,这是代码 $model=new Tblvehicle; $sql="Select tblvehicle.serial_no, tblmodel.description, tbluser.user_name, tbluser.user_code " . "From tblvehicle" . " left join tblmodel " . "on tblvehicle.model_code= tblmodel.model_code" . " left join
$model=new Tblvehicle;
$sql="Select tblvehicle.serial_no, tblmodel.description, tbluser.user_name, tbluser.user_code "
. "From tblvehicle"
. " left join tblmodel "
. "on tblvehicle.model_code= tblmodel.model_code"
. " left join tbluser"
. " on tblvehicle.user_code=tbluser.user_code";
$query= Yii::app()->db->createCommand($sql)->queryScalar();
$dataProvider = new CSqlDataProvider($sql, array('totalItemCount'=>$query));
$this->render('index',array(
'model'=>$model,'dataProvider'=> $dataProvider));
这是我不完整的tblvehile
grid视图-
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tblvehiclegrid',
'dataProvider'=>$dataProvider,
'filter'=>$model,
'columns'=>array(
现在我如何显示这4列serial\u no、description、user\u name、
和user\u code
?因为它们来自不同的表,我不知道如何添加它们
'columns'=>array(
也许我尝试这样做的方式也是错误的。因此,请在这方面需要一些帮助,我对Yii非常陌生。以下是必要的控制器代码
$criteria=new CDbCriteria();
$dataProvider=new CActiveDataProvider('Tblvehicle', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>5,
),
));
return $dataProvider;
$this->render('index',array(
'model'=>$model,'dataProvider'=> $dataProvider));
将以下行添加到TBLVehice模型的relationship部分,使其看起来像这样,只使用4个关系中的两个,阅读代码注释中的why
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(
'rl_model'=>array(self::BELONGS_TO, 'Tblmodel', 'model_code'),//presuming that model_code is the primary key of this table if not use the two below
'rl_user'=>array(self::BELONGS_TO, 'Tbluser', 'user_code'),//presuming that user_code is the primary key of this table if not use the two below
'rl_model' => array(self::BELONGS_TO, 'Tblmodel', '', 'foreignKey' => array('model_code'=>'model_code')), //Non Primary field
'rl_user' => array(self::BELONGS_TO, 'Tbluser', '', 'foreignKey' => array('user_code'=>'user_code')), //Non Primary field
);
}
然后在视图中使用它
'columns'=>array(
'serial_no',
'subject',
array(
'name'=>'Description Code',
'value'=>'$data->rl_model->description',
),
array(
'name'=>'Username',
'value'=>'$data->rl_user->user_name',
),
array(
'name'=>'User Code',
'value'=>'$data->rl_user->user_code',
),
),
基本上,我们不必编写mysql语句和使用联接,而是可以使用关系有效地创建联接。如上图所示,可以随时引用此字段
让我知道你过得怎么样。Thnx先生对此非常着迷。它现在正在工作。只有一个小的修正。我想我们需要使用“header”而不是“name”。@farr没有问题。我之所以使用
name
实际上是因为您无法在不进行更多修改的情况下对自定义列进行排序。这篇文章将告诉你如何排序,如果你需要这个。但是你在你的情况下是正确的标题是正确的。很高兴我能帮忙。