Ad

Laravel OrderByRaw Column Not Found

- 1 answer

I Got a problem with orderByRaw Laravel.

Array:

$arr = [H123456, H7654321];

query:

$ids = implode(',', $arr);
$query = User::whereIn('id', $arr)->isActive()->orderByRaw(DB::raw("FIELD(id,". $ids.")"))->get();

This is the raw query:

"select * from `merchant_heads` where `id` in (?, ?) and `category_id` = ? and `status` = ? order by FIELD(id,Hf561b6fd32aec6ea,H7c81e6fa3f85fc74) limit 10 offset 0"

I've already put this inside my User model:

public $incrementing = false;

When i execute the query it says Column not found: 1054 Unknown column 'Hf561b6fd32aec6ea' in 'order clause'.

I've tried to change $ids with single value like 1 it working. but it's not working if the ID is string like mine.

Any solution?

Ad

Answer

Since the ids are strings, you need to encapsulate them. Luckily, laravel can do it for you. Try with this:

$ids = implode(',', $arr);
$qs = array_fill(0,count($arr),'?');
$query = User::whereIn('id', $arr)->isActive()->orderByRaw(DB::raw("FIELD(id,". implode(',', $qs).")"),$arr)->get();
Ad
source: stackoverflow.com
Ad