M
M
Monitorkin2017-09-27 03:25:01
Yii
Monitorkin, 2017-09-27 03:25:01

Why doesn't sorting and filtering work in GridView in Yii2 with MongoBD by associated field?

We have yii2 + mongodb and two collections Items (products) and Cats (product categories). I deduce in GridView fields from Items + a name of a category from communication "cat". Filtering and sorting fields from the Items collection works fine, category names from the related Cats table are displayed normally, a sort link appears on the column header of the "name" related field, and a filter field appears below it, but nothing happens when clicking on the header to sort, when you enter values ​​in the filter field, nothing happens either. Where is the mistake? Thanks for any help.
Model Items:

class Items extends ActiveRecord {

    public static function CollectionName() {
        return ['local', 'items'];
    }

    public function attributes() {
        return ['_id', 'name', 'cat_id'];
    }

    public function rules() {
        return [;
    }

    public function attributeLabels() {
        return [...];
    }

    public function getCat() {
        return $this->hasOne(Cats::className(), [(string) '_id' => (string) 'cat_id']);
    }    
}

Cats->_id is a mongo ObjectId, Items->cat_id is a string. I also tried to do it without type conversion to string - it did not work.
Model ItemsSearch:
class ItemsSearch extends Items {

    public function attributes() {
        return ['_id', 'name', 'cat_id', 'cat.name'];
    }

    public function scenarios() {
        return Model::scenarios();
    }

    public function search($params) {
        $query = Items::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => 30],
        ]);

        $dataProvider->sort->attributes['cat.name'] = [
            'asc' => ['cat.name' => SORT_ASC],
            'desc' => ['cat.name' => SORT_DESC],
        ];

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

         $query->andFilterWhere([
                '_id' => $this->_id,
                 ...
            ]);

        $query->andFilterWhere(['like', 'cat.name', $this->getAttribute('cat.name')])
               ...;

        return $dataProvider;
    }

}

Model Cats:
class Cats extends ActiveRecord {

    public static function collectionName() {
        return ['local', 'cats'];
    }

    public function attributes() {
        return [
            '_id',
            'name',
            ...
        ];
    }

    public function rules() {
        return [
            [['_id'], 'required'],
            [['name'], 'string'],
        ];
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question