W
W
WebDev2016-08-01 13:13:21
Laravel
WebDev, 2016-08-01 13:13:21

How to sort laravel selection by array?

There is an array of identifiers. I select
$ids = [1, 5, 17, 23];
products by them.
$products = Product::whereIn('id', $ids)->get();
How now to sort the selection so that the first product comes with id = 1, the second id = 5, the third id = 17 and so on?
UPD:
Solution

->orderBy(\DB::raw("FIELD(id, " . implode(',', $entityIds) . ")"))

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Pochepko, 2016-08-01
@kirill-93

$ids = [1, 5, 17, 23];
$products = Product::whereIn('id', $ids)
    ->orderBy(\DB::raw("ORDER BY FIELD(id".implode(',',$ids).")"))
    ->get();

I did. From this article oooportal.ru/?cat=article&id=1227

C
cha-cha, 2016-08-01
@cha-cha

$products = Product::whereIn('id', $ids)
    ->orderBy('id', 'asc')
    ->get();

https://laravel.com/docs/5.2/queries

6
65536, 2016-08-02
@65536

I've always wondered about this issue, but never found a solution. I twist the cycle (it seems that nothing terrible has happened in connection with this yet)

class X
{
    public static function getRowsByField($rows, $field)
    {
        $output = [];
        foreach ($rows as $row) {
            $output[$row[$field]] = $row;
        }

        return $output;
    }
}

$ids = [1, 5, 17, 23];

$products = Product::whereIn('id', $ids)->get();

$productsById = X::getRowsByField($products, 'id');

foreach ($ids as $id) {
     ....$productsById[$id]...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question