Yii2实现让关联字段支持搜索功能的方法

时间:2022-12-13 08:06:31

本文实例讲述了Yii2实现让关联字段支持搜索功能的方法。分享给大家供大家参考,具体如下:

这里有两张表,表结构如下,companies_compay_id 为外键

yii2advanced.branches表:

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','inactive')

yii2advanced.companies表:

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','inactive')

在上面表中,可以用companiesCompany.company_name来获取公司名,不过这样是不支持搜索的。

想要支持搜索功能,需要在branches的index视图添加以下代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?= 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方法为:

?
1
2
3
4
5
6
7
public function rules()
{
  return [
    [['branch_id'], 'integer'],
    [['branch_name', 'branch_address', 'branch_created_date', 'branch_status','companies_company_id'], 'safe'],
  ];
}

修改search方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;

刷新页面即可看到

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。