I have two tables, one is products and the other is varients.
In product table I store product basic data such as name, image, brand, etc. In varients table I store variants of product such as 1kg, 2kg, 5kg, etc
varients Table
id | product_id | varientName | price |
---|---|---|---|
1 | 1 | 2kg | 100 |
2 | 1 | 1kg | 50 |
3 | 1 | 5kg | 480 |
4 | 2 | 250g | 25 |
5 | 2 | 100g | 10 |
6 | 2 | 500g | 50 |
products Table
id | Name |
---|---|
1 | rice |
2 | tea |
I want to fetch data from both table such as – one product variant which one has lowest price.
I try this:
$bestSellingProduct = DB::table('products')
->join('varients', 'products.id', '=', 'varients.product_id')
->select('products.product_id','products.name',,'varients.varientName','varients.id','varients.price')
->orderBy('varients.varientPrice','ASC')
->groupby('products.id')
->get();
I want to fetch products and their variants, such as rice 1kg (50) and tea 100g (50).
2
Answers
Basic SQL for finding minimum value and also other columns of the min value record can be achieved using
window
function:If you don’t want to use Eloquent then do it like this.
and if want to use Eloquent then do it like this and I assume that you have the all the relationships already there.