Yii2 allows associated fields to support the search function.
This example describes how to enable the associated fields to support the search function in yii2. We will share this with you for your reference. The details are as follows:
There are two tables. The table structure is as follows. companies_compay_id is a foreign key.
Yii2advanced. branches table:
Branch_id: int (11)
Companies_company_id: int (11)
Branch_name: varchar (100)
Branch_address: varchar (255)
Branch_created_date: datetime
Branch_status: enum ('active', 'inactivity ')
Yii2advanced. companies table:
Company_id: int (11)
Company_name: varchar (100)
Company_email: varchar (100)
Company_address: varchar (255)
Logo: varchar (200)
Company_start_date: datetime
Company_create_date: datetime
Company_status: enum ('active', 'inactivity ')
In the above table, you can use companiesCompany. company_name to obtain the company name, but this does not support searching.
To support the search function, add the following code in the index view of branches:
<? = GridView: widget (['dataprovider' => $ dataProvider, 'filtermodel' => $ searchModel, 'columns' => [['class' => 'yii \ grid \ SerialColumn '], // The added code starts with ['label' => 'Company name ', 'attribute' => 'companies _ company_id ', 'value' => 'companiescompany. company_name '], // The added code ends with 'companiescompany. company_name ', // 'Branch _ id', // 'company_company_id', 'Branch _ name', 'Branch _ address', 'Branch _ created_date ', // 'Branch _ s Tatus ', ['class' => 'yii \ grid \ actioncolumn'],],]);?>
Then modify SearchBranches. php
Modify the rules method:
public function rules(){ return [ [['branch_id'], 'integer'], [['branch_name', 'branch_address', 'branch_created_date', 'branch_status','companies_company_id'], 'safe'], ];}
Modify the search method:
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 ;} // Add the following line of code $ 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]) // Add the following line of code-> andFilterWhere (['like', 'companies. company_name ', $ this-> companies_company_id]); return $ dataProvider;
Refresh the page to see