I have 2 models:
- Product, which has
sort
field. - Stock, which has product_id and quantity fields.
I want to get products ordered by sort field (ASC) but the products which stocks quantity equals 0 need to be in the end of list.
E.g.
Products
id sort
1 3
2 4
3 2
4 1
Stock
product_id quantity
1 2
1 3
2 5
3 0
4 2
Expected List (Product IDs) - 4, 1, 2, 3
I have written the SQL query for what i need to do.
select p.url, p.sort, s.tot
from products p
inner join (select product_id, sum(quantity) as tot from stocks group by product_id) s on p.id = s.product_id
order by case when s.tot = 0 then 1 else 0 end, p.sort asc
Here is the relation of Product -> Stock
public function stocks() {
return $this->hasMany('\App\Stock', 'product_id');
}
Is there a way to get this kind of listing using Eloquent Model's scopes?
UPDATE
The solution.
public function scopeOrdered($query, $notInStock = false)
{
if($notInStock)
return $query->join(DB::raw("(
select product_id, sum(quantity) as tot
from stocks
group by product_id
) s"), 'products.id', '=', 's.product_id')->orderByRaw("case when s.tot = 0 then 1 else 0 end, products.sort ASC");
else
return $query->orderBy('sort', 'asc');
}