Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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;
}
}
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',
],
],
]);
'name' => [
'asc' => ' ASC NULLS FIRST', // PostgreSQL specific feature
'desc' => ' DESC NULLS LAST',
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question