标签:
在使用yii2构建搜索视图,经常都会使用到gridview这个组件,这个组件十分强大,通过一定的配置就能进行关联搜索,下面就是简单的步骤
需求场景:一个车系表,里面存放在品牌表的id,现在要用品牌名字进行like搜索对应的车系
1、用gii生成一个与Model对应的Search;
2、在Search中,增加一个属性,名为$brand_name;
class SeriesSearch extends Series { public $brand_name; // 品牌名字,随便起名
3、在Search中search中,添加这两句代码;
public function search($params) { $query = Series::find(); $query->joinWith([‘brand‘]); // 连接品牌表,此处不用写全名 $dataProvider = new ActiveDataProvider([ ‘query‘ => $query, ‘sort‘=>[ ‘defaultOrder‘ => [‘id‘=>SORT_DESC] ] ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ ‘id‘ => $this->id, ‘brand_id‘ => $this->brand_id, ‘level_id‘ => $this->level_id, ‘type_id‘ => $this->type_id, ‘is_hot‘ => $this->is_hot, ‘auto_series_id‘ => $this->auto_series_id, ‘status‘ => $this->status, ‘sort‘ => $this->sort, ‘min_price‘ => $this->min_price, ‘max_price‘ => $this->max_price, ‘car_total‘ => $this->car_total, ‘create_time‘ => $this->create_time, ‘update_time‘ => $this->update_time, ]); $query->andFilterWhere([‘like‘, ‘name‘, $this->name]) ->andFilterWhere([‘like‘, ‘letter‘, $this->letter]) ->andFilterWhere([‘like‘, ‘comments‘, $this->comments]) ->andFilterWhere([‘like‘, ‘t_brand.name‘, $this->brand_name]); // 此处必须写表全名,而$this->brand_name指向的属性正是第二步中新增的属性 return $dataProvider;
}
4、此时,再来看看视图文件;
[ ‘label‘ => ‘品牌‘, ‘attribute‘ => ‘brand_name‘, // 此处是第二步新增的属性名字 ‘value‘ => ‘brand.name‘, // 不用写表全名 ],
5、到此,就大功告成了!
标签:
原文地址:http://www.cnblogs.com/xyb-php/p/4377494.html