duanhe6718
duanhe6718
2016-02-23 10:11

Yii2:在gridview中显示和过滤关系表

已采纳

I have two tables: people & categories

People

- id
- name
- ...

Categories

- id
- name
- description

And another table with the relation between both as one person can have multiple categories assigned:

PeopleCategoriesAssn

- peopleID
- categoryID

I can show the categories IDs in my gridview (views/people/index.php) with:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ...,
        [
            'label' => 'Category',
            'value' => function ($data) {
                $output = '';
                foreach($data->peopleCategoriesAssns as $request) {
                    $output .= $request->talentCategoryID.'<br>';
                }
                return $output;
            },
        ],
        ...

which uses this from models/People.php

public function getPeopleCategoriesAssns() 
{ 
    return $this->hasMany(PeopleCategoriesAssn::className(), ['peopleID' => 'id']); 
} 

How could I show the categories names instead of the categoies IDs within the gridview and also, what should i do at /models/PeopleSearch.php in order to allow search/filter on that field?

Thank you in advance,

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongzhi8984 dongzhi8984 5年前

    There are two parts involved with your problem.

    1. Showing the values

    This is just a respecification of your GridView-column:

    'columns'=>[
        //...
        [
            'attribute'=>'catNameSearch',
            'value'=>function ($model, $key, $index, $column) {
                $cats = $model->peopleCategoriesAssns;
                if (empty($cats)) {
                    return null;
                } else {
                    return implode(', ', ArrayHelper::getColumn($cats, 'name');
                }
            },
        ],
        //...
    ]
    

    2. Searching cat names

    Now to solve the problem of searching them it gets a little more complex. As you can see I set the attribute above to catNameSearch. You need to add this as a public var to your PeopleSearch-class and declare it as safe in a validator of the search-class.

    class PeopleSearch extends \app\models\People
    {
    
        public $catNameSearch;
    
        public function rules()
        {
            return [
                //...
                [['catNameSearch'], 'safe'],
                //...
            ];
        }
     }
    

    In the search-method itself you add a sub-query to show only people assigned to the corresponding category. This could be done like so:

    if (!empty($this->catNameSearch)) {
        $peopleIdsMatching = PeopleCategoriesAssn::find()
             ->select('peopleID')
             ->distinct(true)
             ->joinWidth('category')
             ->andWhere(['like', ['category.name'=>$this->catNameSearch]])
            ->column();
    
         $this->andWhere(['id'=>$peopleIdsMatching]);
    }
    

    Now only people with a relation to the given category will be shown. This could be further optimized with performing the comparison in an actual sub-query of the people-search and not doing a seperate query, but this should give you the basic idea!

    点赞 评论 复制链接分享
  • dongxing9219 dongxing9219 5年前

    To answer the first part you need to add another method to the People class:

    public function getCategories() {
        return $this->hasMany( Categories::className(), [ 'id' => 'categoryID' ] )
                    ->via('PeopleCategoriesAssn');
    }
    

    See: http://www.yiiframework.com/doc-2.0/yii-db-activerelationtrait.html#via()-detail

    This will allow you to do:

    foreach( $data->categories as $category) {
        $output .= $category->name.'<br>';
    }
    

    As for searching, I'm not sure, but adding public $categoryName property to the search class would be a good starting point.

    点赞 评论 复制链接分享