D
D
des1roer2017-11-21 13:34:25
css
des1roer, 2017-11-21 13:34:25

Yii2 custom sorting in api?

need to implement a request specific to pg view

SELECT * FROM "related_item" ORDER BY position = 2 DESC, position = 1 DESC, position = 3 ASC

for api like api/item/?sort={position:2,position:1,-position:3}
i.e. how to override /vendor/yiisoft/yii2/data/Sort.php has
anyone come across something like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
des1roer, 2017-11-21
@des1roer

class Sort extends \yii\data\Sort
{
    /**
     * @inheritdoc
     */
    public function getOrders($recalculate = false): array
    {
        $orders = [];
        $request = Yii::$app->getRequest();
        $params = $request->getQueryParams();
        if (isset($params[$this->sortParam])) {
            $sortParams = explode(',', $params[$this->sortParam]);
            foreach ($sortParams as $rawField) {
                $field = explode(':', ltrim($rawField, '-'));
                $sort = 'ASC';
                if (($rawField{0} == '-')) {
                    $sort = 'DESC';
                }
                if (in_array($field[0], array_keys($this->attributes)) && !empty($field[1])) {
                    $value = (int) $field[1];
                    $orders[] = (new Expression("$field[0] = $value $sort"));
                }
            }
        }

        $orders = ArrayHelper::merge(
            $orders,
            parent::getOrders($recalculate)
        );

        return $orders;
    }
}

M
Maxim Timofeev, 2017-11-21
@webinar

Do you need sort? If you have a dataProvider there, then it's probably easier to change the query
If all the same, sort should work like this:

$sort = new Sort([
        'attributes' => [
            'position' => [
                'default' => 'position = 2 DESC, position = 1 DESC, position = 3 ASC',
            ],
        ],
    ]);

But in general , starting from version 2.0.12 , you can do this:
'name' => [
    'asc' => ' ASC NULLS FIRST', // PostgreSQL specific feature
    'desc' => ' DESC NULLS LAST',
]

here are the docs: www.yiiframework.com/doc-2.0/yii-data-sort.html#$a...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question