当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Laravel eloquent, how to order custom sortby

问题描述:

I have the following code that works fine:

$products = Product::like($search)->whereIn('id', $request->input('product_ids'))->skip($offset)->take($limit)->get(array('products.*'))->sortBy(function($product) use ($sort_order) {

$number = (isset($sort_order[$product->id])) ? $sort_order[$product->id] : 0;

return $number;

});

This returns the items in ascending order, how do I specify whether I want sortby to return the products in ascending or descending order?

网友答案:
//$order contains either 'asc' or 'desc'
$products = Product::like($search)->whereIn('id', $request->input('product_ids'))->skip($offset)->take($limit)->get(array('products.*'))->sortBy(function($product) use ($sort_order, $direction) {
    $number = (isset($sort_order[$product->id])) ? $sort_order[$product->id] : 0;
    return ($direction == 'asc') ? $number : -$number;
});
网友答案:

I really don’t understand the query. There’s a lot going on there that really shouldn’t be. For example:

  • You’re not selecting data from any other table, so why are you specifying all rows from the products table in the get() method (->get(array('products.*')))?
  • Why are you applying the ordering function to the returned collection instead of just applying the order clause to the query?

With the above, you query could be simplified to something like:

$productIds = [1, 2, 3, 4];

$direction = 'asc'; // or desc

$products = Product::like($search)
                   ->whereIn('id', $productIds)
                   ->skip($offset)
                   ->take($limit)
                   ->orderBy('id', $direction)
                   ->get();

Also, you don’t need to manually specify the offset and limit if you use the paginate() helper method.

分享给朋友:
您可能感兴趣的文章:
随机阅读: