Laravel: order by where in

丶灬走出姿态 提交于 2019-11-27 01:12:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!