Laravel: How to get custom sorted eloquent collection using whereIn method

后端 未结 2 531
余生分开走
余生分开走 2021-01-18 06:22

I have an array of product ids against which I need to retrieve the model collection. The array is something like this:

$ids = array(9, 2, 16, 11, 8, 1, 18);         


        
相关标签:
2条回答
  • 2021-01-18 06:40

    Use Field() function of mysql (If you are using mysql database) with DB::raw() of laravel something like

    $products = Product::whereIn('id', $ids)
        ->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
        ->get();
    

    Field() returns the index position of a comma-delimited list

    0 讨论(0)
  • 2021-01-18 06:45

    Here's another way to do that.

    $ids = array(9, 2, 16, 11, 8, 1, 18);
    $products = User::whereIn('id', $ids)->orderByRaw('FIELD(id, '.implode(',', $ids).')')->get();
    
    0 讨论(0)
提交回复
热议问题