Answer the question
In order to leave comments, you need to log in
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
$ids = [1, 5, 17, 23];
$products = Product::whereIn('id', $ids)
->orderBy(\DB::raw("ORDER BY FIELD(id".implode(',',$ids).")"))
->get();
$products = Product::whereIn('id', $ids)
->orderBy('id', 'asc')
->get();
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 questionAsk a Question
731 491 924 answers to any question