首页  >  文章  >  php教程  >  Yii2实现让关联字段支持搜索功能的方法

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

高洛峰
高洛峰原创
2016-12-23 16:42:591120浏览

本文实例讲述了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视图添加以下代码:

<?= GridView::widget([
  &#39;dataProvider&#39; => $dataProvider,
  &#39;filterModel&#39; => $searchModel,
  &#39;columns&#39; => [
    [&#39;class&#39; => &#39;yii\grid\SerialColumn&#39;],
    //添加的代码开始
    [
      &#39;label&#39;=>&#39;公司名&#39;,
      &#39;attribute&#39;=>&#39;companies_company_id&#39;,
      &#39;value&#39;=>&#39;companiesCompany.company_name&#39;
    ],
     //添加的代码结束
    &#39;companiesCompany.company_name&#39;,
    // &#39;branch_id&#39;,
    // &#39;companies_company_id&#39;,
    &#39;branch_name&#39;,
    &#39;branch_address&#39;,
    &#39;branch_created_date&#39;,
    // &#39;branch_status&#39;,
    [&#39;class&#39; => &#39;yii\grid\ActionColumn&#39;],
  ],
]); ?>

然后修改SearchBranches.php

修改rules方法为:

public function rules()
{
  return [
    [[&#39;branch_id&#39;], &#39;integer&#39;],
    [[&#39;branch_name&#39;, &#39;branch_address&#39;, &#39;branch_created_date&#39;, &#39;branch_status&#39;,&#39;companies_company_id&#39;], &#39;safe&#39;],
  ];
}

   

修改search方法:

public function search($params)
{
  $query = Branches::find();
  $dataProvider = new ActiveDataProvider([
    &#39;query&#39; => $query,
  ]);
  $this->load($params);
  if (!$this->validate()) {
    // uncomment the following line if you do not want to any records when validation fails
    // $query->where(&#39;0=1&#39;);
    return $dataProvider;
  }
  // 添加下面这行代码
  $query->joinWith(&#39;companiesCompany&#39;);
  $query->andFilterWhere([
    &#39;branch_id&#39; => $this->branch_id,
  //  &#39;companies_company_id&#39; => $this->companies_company_id,
    &#39;branch_created_date&#39; => $this->branch_created_date,
  ]);
  $query->andFilterWhere([&#39;like&#39;, &#39;branch_name&#39;, $this->branch_name])
    ->andFilterWhere([&#39;like&#39;, &#39;branch_address&#39;, $this->branch_address])
    ->andFilterWhere([&#39;like&#39;, &#39;branch_status&#39;, $this->branch_status])
     // 添加下面这行代码
    ->andFilterWhere([&#39;like&#39;, &#39;companies.company_name&#39;, $this->companies_company_id]);
  return $dataProvider;

   

刷新页面即可看到

更多Yii2实现让关联字段支持搜索功能的方法相关文章请关注PHP中文网!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn