首先,数据库方面是这样的 一个学生表Stu,一个成绩表Score。这两个表的关联关系是 Score表中的stuid关联学生表中的id。也就是一个学生有多条成绩记录。gii在生成Score模型的时候会生成hasOne方法函数。
public function getStu() { return $this->hasOne(Stu::className(), ['id' => 'stuid']); }
接下来,主要是修改成绩表的搜索模型,直接贴个完整代码吧,修改的地方有注释
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Score; use app\models\Stu; class SearchScore extends Score { // 自定义字段, public $sfzh; public $xm; public $bmh; public function rules() { return [ [['id', 'stuid', 'kmid'], 'integer'], [['code', 'cj', 'year', 'dj'], 'safe'], // 自定义字段添加验证规则 [['sfzh', 'xm', 'bmh'], 'safe'], ]; } public function scenarios() { return Model::scenarios(); } public function search($params) { $query = Score::find(); // 联合查询 学生表 $query->joinWith(['stu']); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); // 自定义字段 $dataProvider->setSort([ 'attributes' => [ 'sfzh' => [ 'sfzh' => ['stu.sfzh' => SORT_ASC], 'desc' => ['stu.sfzh' => SORT_DESC], 'label' => '身份证号', ], 'xm' => [ 'xm' => ['stu.xm' => SORT_ASC], 'desc' => ['stu.xm' => SORT_DESC], 'label' => '姓名', ], 'bmh' => [ 'bmh' => ['stu.bmh' => SORT_ASC], 'desc' => ['stu.bmh' => SORT_DESC], 'label' => '报名号', ], ] ]); $this->load($params); if (!$this->validate()) { return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ //'id' => $this->id, 'stuid' => $this->stuid, 'kmid' => $this->kmid, ]); // 添加联合查询的 条件 精确值直接指向 $query->andFilterWhere([ 'stu.sfzh' => $this->sfzh, 'stu.bmh' => $this->bmh, ]); $query->andFilterWhere(['like', 'code', $this->code]) ->andFilterWhere(['like', 'cj', $this->cj]) ->andFilterWhere(['like', 'year', $this->year]) ->andFilterWhere(['like', 'dj', $this->dj]); // 添加联合查询的 条件 模糊值 用like $query->andFilterWhere(['like', 'stu.xm', $this->xm]) ; return $dataProvider; } }
最后就是在视图中修改GridView要显示的字段,例如 sfzh字段
[ 'attribute'=>'sfzh', 'label'=>'身份证号', 'value' => function($model) { if($model->stu !== null){ return $model->stu->sfzh; } }, ],
这样就可以和搜索学生表一样来依据学生信息加载成绩数据了。解决了 多对一数据的搜索模型改造。