简体   繁体   中英

Laravel OrderByRaw column not found

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM