1

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?

ssuhat
  • 7,387
  • 18
  • 61
  • 116

1 Answers1

2

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();
aynber
  • 22,380
  • 8
  • 50
  • 63
  • It's working perfectly. If you don't mind can you explain a little bit about `array_fill` ? – ssuhat Jan 11 '16 at 14:44
  • 1
    It creates an array with the length and values you specify. So in this case, it's creating an array with the exact number of question marks/placeholders as you have ids. Information on the function is at http://php.net/manual/en/function.array-fill.php . – aynber Jan 11 '16 at 14:47