Sort and filter data in GridView Yii2 where column is not in database

后端 未结 3 565
孤独总比滥情好
孤独总比滥情好 2020-12-28 23:38

If I have 2 fields in db - probability and influence and I need a column in GridView where these two fields are multiplied. I managed to add it there like:

          


        
相关标签:
3条回答
  • 2020-12-29 00:00

    Removed

          $query->select('*, (probability * influence) as priority');
    

    changed

              'priority' => [
                    'asc' => ['(probability * influence)' => SORT_ASC],
                    'desc' => ['(probability * influence)' => SORT_DESC],
                    'label' => 'Priority',
                  ],
    

    and after $this->load($params);

              $query->andFilterWhere(['=', '(probability * influence)', $this->priority]);
    

    And search works as needed! :)

    Thanks for help!

    0 讨论(0)
  • 2020-12-29 00:03

    Here is my solution, which works for sorting non-table field

         $dataProvider->sort->attributes['customer'] = [
            'asc' => ['customer' => SORT_ASC],
            'desc' => ['customer' => SORT_DESC],
        ];
    
    0 讨论(0)
  • 2020-12-29 00:12

    STEP 1: Add a getter function to your base Risks model:

    public function getPriority() {
        return ($this->probability * $this->influence);
    }
    

    STEP 2: Add an attribute priority to your model RisksSearch and configure your rules.

    /* your calculated attribute */
    public $priority;
    
    /* setup rules */
    public function rules() {
       return [
           /* your other rules */
           [['priority'], 'safe']
       ];
    }
    

    STEP 3: Edit the search() method to include the calculated field priority

    public function search($params) {
    
        $query = Person::find();
    
        $query->select('*, (probability * influence) as priority');
    
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
    
        /**
         * Setup your sorting attributes
         * Note: This is setup before $this->load($params)
         */
        $dataProvider->setSort([
            'attributes' => [
                'id',
                'priority' => [
                    'asc' => ['priority' => SORT_ASC],
                    'desc' => ['priority' => SORT_DESC],
                    'label' => 'Priority',
                    'default' => SORT_ASC
                ],
            ]
        ]);
        ...
    

    STEP 4: Add $query->andFilterWhere() after $this->load($params) to be able to filter the calculated field

    // use the operator you wish, i.e. '=', '>', '<' etc
    $query->andFilterWhere(['=', '(probability * influence)', $this->priority]);
    
    0 讨论(0)
提交回复
热议问题