John Davidson

php - Laravel does not give the values sequentially

0 comments
Message:


I have a car ids array.


$carIds = [21,12,33];

I'm sending an ids array to retrieve values from my collection.


$cars = Cars::whereIn('id', $carIds)->get();

Incoming car values do not come in the order of id I gave, it is complicated.



My Answer:
>get();

In Laravel, when you use the `whereIn` method to retrieve values from a collection based on an array of IDs, the values are not guaranteed to be returned in the same order as the IDs in the array. The database query will return the values based on the order in which they are retrieved from the database, which may not necessarily match the order of the IDs in the array.

If you need to ensure that the values are returned in the same order as the IDs in the array, you can use the `orderByRaw` method to specify the order in which the values should be returned. For example:

php
$cars = Cars::whereIn('id', $carIds)
->orderByRaw(DB::raw("FIELD(id, " . implode(',', $carIds) . ")"))
->get();


This will order the values based on the order of the IDs in the `$carIds` array.

Rate this post

5 of 5 based on 1621 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us