Laravel: order by where in

前端 未结 3 1799
盖世英雄少女心
盖世英雄少女心 2020-12-08 04:59

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

3条回答
  •  抹茶落季
    2020-12-08 05:30

    Solution:

    $ids = array(1,17,2);
     
    $ids_ordered = implode(',', $ids);
     
    $items = static::whereIn('id', $ids)
     ->orderByRaw("FIELD(id, $ids_ordered)")
     ->get();
    

    Additional Notes:

    Using the solution found on an article titled Get all items at once ordered by the current order of ids in the WHERE IN clause using Eloquent:

    Useful when you want to orderBy the items from the database using the order of id's in the array you supplied in the WHERE IN clause. Can be easily modified to suit your needs, like provide a different order of ids to be used.

    // Raw SQL:
    // SELECT * FROM items WHERE id IN (1,2,3,4,5) ORDER BY FIELD(id,1,2,3,4,5);
     
    $itemIds = array(1,2,3,4,5);
     
    $ids = implode(',', $itemIds);
     
    $items = static::whereIn('id', $itemIds)
        ->orderByRaw(DB::raw("FIELD(id, $ids)"))
        ->take($limit)
        ->get();
    

提交回复
热议问题