V
V
Vlad Osadchyi2018-12-13 16:31:33
MySQL
Vlad Osadchyi, 2018-12-13 16:31:33

How to make a specific entry appear first when sorting alphabetically?

In general, there is a method

public function getCountries()
    {
        $countries = ArrayHelper::map(Countries::find()
            ->orderBy(['name' => SORT_ASC])
            ->asArray()
            ->all(), 'id', 'name');

        return $countries;
    }

I think it’s clear what he does) But I need to make the first country in the list have a certain id, for example 220, and then all the others in alphabetical order, how can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy Orlov, 2018-12-14
@VladOsadchyi

->orderBy([
    new \yii\db\Expression('FIELD (id, 220)'),
    'name' => SORT_ASC,
]);

in general, google about "\yii\db\Expression" and "ORDER BY FIELD"
or so :)
....
unset($countries[220]);
$countries = [220 => 'Country Name'] + $countries;
return $countries;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question