我建議不要使用原始SQL,尤其是希望提供搜索字段時,因爲這提供了一個潛在的應用程序中的漏洞,並打開SQL注入攻擊的可能性。相反,我會鼓勵使用Yiis查詢構建器或DAO,如here所述。
這樣說,我已經用Yiis內置的查詢生成器重寫了你的代碼。
public function actionAnalisa()
{
// store any $_GET parameters passed for filtering via GridView
$params = Yii::$app->request->queryParams;
// use query builder instead of raw SQL to avoid SQL injection attacks
$query = (new Query())
->select([
'permohonan_id' => 'tbl_permohonan.permohonan_id',
'id' => 'user.id',
'bm_id' => 'tbl_moderator.bm_id',
'unit_kampuscawangan' => 'tbl_bhgnmod.unit_kampuscawangan',
'bahagian_nama' => 'tbl_bahagian.bahagian_nama',
'unit_nama' => 'tbl_unit.unit_nama'
])
->from('tbl_permohonan')
->join('INNER JOIN', 'user', 'tbl_permohonan.user_id=user.id')
->join('INNER JOIN', 'tbl_moderator', 'user.id=tbl_moderator.user_id')
->join('INNER JOIN', 'tbl_bhgnmod', 'tbl_moderator.bm_id=tbl_bhgnmod.bm_id')
->join('INNER JOIN', 'tbl_bahagian', 'tbl_bhgnmod.bahagian_id=tbl_bahagian.bahagian_id')
->join('INNER JOIN', 'tbl_unit', 'tbl_bhgnmod.unit_id=tbl_unit.unit_id');
// Adds additional WHERE conditions to the existing query but ignores empty operands
$query->andFilterWhere(['like', 'tbl_permohonan.permohonan_id', $params['pid']])
->andFilterWhere(['like', 'user.id', $params['id']])
->andFilterWhere(['like', 'tbl_moderator.bm_id', $params['bm_id']])
->andFilterWhere(['like', 'tbl_bhgnmod.unit_kampuscawangan', $params['unitk']])
->andFilterWhere(['like', 'tbl_bahagian.bahagian_nama', $params['banama']])
->andFilterWhere(['like', 'tbl_unit.unit_nama', $params['unnama']]);
// an ActiveDataProvider will accept a Query object instead of raw SQL
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('analisis', [
'dataProvider' => $dataProvider,
]);
}
請記住,您將不得不將以下內容添加到控制器文件的頂部。
use yii\data\ActiveDataProvider;
use yii\db\Query;
爲了使您的視圖文件的GridView控件裏搜索字段,你必須指定一個filterModel,如解釋here。
GridView中的列允許您指定過濾器屬性,該過濾器屬性將使用屬性指定的HTML在列頂部呈現過濾器單元格。這些過濾器通過GET自動提交到同一頁面,這就是爲什麼它們已經在控制器中使用此GridView中指定的名稱進行處理。
<?
use yii\helpers\Html;
use yii\grid\GridView;
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// filterModel must be set to render filter cells within GridView
'filterModel' => true,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
// specify attribute to display
'attribute' => 'permohonan_id',
// filter attribute accepts HTML to render
// in this case an input field of type string, with a name of 'pid'
'filter' => Html::input('string', 'pid')
],
[
'attribute' => 'id',
'filter' => Html::input('string', 'id')
],
[
'attribute' => 'bm_id',
'filter' => Html::input('string', 'bmid')
],
[
'attribute' => 'unit_kampuscawangan',
'filter' => Html::input('string', 'unitk')
],
[
'attribute' => 'bahagian_nama',
'filter' => Html::input('string', 'banama')
],
[
'attribute' => 'unit_nama',
'filter' => Html::input('string', 'unnama')
],
],
]); ?>
創建過濾器的模型。在網格配置中將模型添加到'filterModel'。 – Vitaly