A
A
akula222018-05-27 10:46:21
Yii
akula22, 2018-05-27 10:46:21

How to pull out the ID in AR in the order I need?

There is a list of IDs in a certain order, for example 2, 3, 1, 5,
I need to get records from the table in this order, I do
Table::find() ->where(['id' =>$ids])->all();
it but I get records in ascending order, i.e. 1, 2, 3, 5
and I need 2.3, 1,5
in query log
WHERE `id` IN ('2', '3', '1', '5')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Kim, 2018-05-27
@akula22

$items = Table::find()->where(['id' =>[1, 2, 3, 5]])->indexBy('id')->all();
$items = array_replace([2 => null, 3 => null, 1 => null, 5 => null], $items);

S
Sergey Zimoglyadov, 2018-05-27
@wppdevelop

You need to add sorting by the field, according to which the records will line up in the desired order:
By specifying the sort order SORT_ASC or SORT_DESC
By default, sorting is by the primary key, the sort order is "ascending"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question