Tags
Asked 3 years ago
17 Jun 2021
Views 279
Harley

Harley posted

order by where in , Laravel ?

order by where in , Laravel ?
noob

noob
answered Apr 27 '23 00:00

You can use the whereIn() method in combination with the order By() method to order the results based on a specific order of values in a WHERE IN clause. Here's an example:


$

ids = [1, 3, 2];

$users = DB::table('users')
            ->whereIn('id', $ids)
            ->orderByRaw(DB::raw("FIELD(id, " . implode(',', $ids) . ")"))
            ->get();

In this example, we use the whereIn() method to select all users where the id column is in the array $ids. We then use the orderByRaw() method to order the results based on the order of the values in $ids.

The orderByRaw () method allows us to specify a raw SQL expression as the order by clause. In this case, we use the FIELD() function to order the results based on the order of the values in $ids. The FIELD() function returns the index of the first argument in the list of subsequent arguments. In this case, the first argument is the id column and the subsequent arguments are the values in $ids. By passing the values in $ids as a comma-separated string using the implode() function, we can construct the list of arguments dynamically based on the values in the array.

Note that the FIELD() function is a MySQL-specific function and may not be available in other database systems. If you are using a different database system, you may need to use a different function or approach to achieve the same result
Post Answer