Home > front end >  how to get ->orderBy('holding' > 0) in laravel eloquent query?
how to get ->orderBy('holding' > 0) in laravel eloquent query?

Time:09-10

I have a holding(inventory) field in my product table,

I want to get products first that have holding > 0 and on last the products with holding <= 0.

$products = Product::orderBy('holding' , 'desc')->orderBy('id' , 'desc')->paginate(27);

the above query has problem that sorting by 'holding' number, I want to sorting by id, and the product with holding <= 0 goes to last page of pagination.

thanks

CodePudding user response:

You can create tow collections. First with holding >0 and then with holding <=0 and then merge both collections.

$products = Product::where('holding','>',0)->orderBy('id' , 'desc')->get();

$otherProducts = Product::where('holding','<=',0)->orderBy('id' , 'desc')->get();

$products->concat($otherProducts);

$products->paginate(27);

CodePudding user response:

->orderByRaw(
     "CASE WHEN holding > 0 THEN 0 ELSE 1 END DESC"
)
  • Related