问题
I am using SphinxSearch to query some contents and have the ids of my objects that I want to query with MySQL. The array of my ids are sorted depending on their rank Sphinx gives. Thus, I would like to make a MySQL like so:
SELECT * FROM table WHERE id IN (1,17,2)
ORDER BY FIELD(id,1,17,2)
I know I can do:
Table::whereIn('id', $ids)->get();
But I can't get the order I had.
How can I do that in a proper way with Laravel ?
回答1:
Using the solution found on http://laravelsnippets.com/snippets/get-all-items-at-once-ordered-by-the-current-order-of-ids-in-the-where-in-clause-using-eloquent
$ids = array(1,17,2);
$ids_ordered = implode(',', $ids);
$items = static::whereIn('id', $ids)
->orderByRaw(DB::raw("FIELD(id, $ids_ordered)"))
->get();
回答2:
I got this problem too, but my target array elements were strings. in this case ...
$strings = array('xxx','yyy','zzz');
$imploded_strings = implode("','", $strings);
$items = static::whereIn('some_column', $strings)
->orderByRaw(DB::raw("FIELD(some_column, '$imploded_strings')"))
->get();
来源:https://stackoverflow.com/questions/26704575/laravel-order-by-where-in