P
P
Pavel Gogolinsky2016-02-24 16:55:52
Yii
Pavel Gogolinsky, 2016-02-24 16:55:52

How to sort string field as integer?

Request for a selection of goods, sorted by capacity.

$products = Product()::find()->orderBy(['power' => SORT_ASC])->active()->all();

The catch is that in the database the power value is stored as a string and it is sorted in this
1000, 600, 750, 800, 900, 950
way
600, 750, 800, 900, 950, 1000.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Gogolinsky, 2016-02-24
@gogolinsky

Used the mysql CAST function

$sort = new Sort([
                        'attributes' => [
                            'power' => [
                                'asc' => [new Expression('CAST(' . AttributeValue::tableName() . '.value as SIGNED) ASC')],
                                'desc' => [new Expression('CAST(' . AttributeValue::tableName() . '.value as SIGNED) DESC')],
                                'default' => SORT_DESC,
                                'label' => 'Мощность',
                            ],
                        ],
                    ]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question