本文實例講述了Yii2實現讓關聯字段支援搜尋功能的方法。分享給大家參考,具體如下:
這裡有兩張表,表結構如下,companies_compay_id 為外鍵
yii2advanced.branches表:
branch_id:int(11)
comches表:
branch_id:int(11)
comches :varchar(100)
branch_address:varchar(255)
branch_status:enum('active','inactive')
yii2advanced.com('actives)
)
company_email:varchar(100)
company_address:varchar(255)
logo:varchar(200)
company_start_date:datetime
company_create_date:datetime
pany_statintime
company_status:enum)'可以用companiesCompany.company_name來取得公司名,但這樣是不支援搜尋的。
想要支持搜索功能,需要在branches的index視圖添加以下代碼:
<?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], //添加的代码开始 [ 'label'=>'公司名', 'attribute'=>'companies_company_id', 'value'=>'companiesCompany.company_name' ], //添加的代码结束 'companiesCompany.company_name', // 'branch_id', // 'companies_company_id', 'branch_name', 'branch_address', 'branch_created_date', // 'branch_status', ['class' => 'yii\grid\ActionColumn'], ], ]); ?>
然後修改SearchBranches.php
修改rules方法為:
public function rules() { return [ [['branch_id'], 'integer'], [['branch_name', 'branch_address', 'branch_created_date', 'branch_status','companies_company_id'], 'safe'], ]; }
修改search方法:
public function search($params) { $query = Branches::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } // 添加下面这行代码 $query->joinWith('companiesCompany'); $query->andFilterWhere([ 'branch_id' => $this->branch_id, // 'companies_company_id' => $this->companies_company_id, 'branch_created_date' => $this->branch_created_date, ]); $query->andFilterWhere(['like', 'branch_name', $this->branch_name]) ->andFilterWhere(['like', 'branch_address', $this->branch_address]) ->andFilterWhere(['like', 'branch_status', $this->branch_status]) // 添加下面这行代码 ->andFilterWhere(['like', 'companies.company_name', $this->companies_company_id]); return $dataProvider;
刷新頁面即可看到
更多Yii2實現讓關聯字段支援搜尋功能的方法相關文章請關注PHP中文網!