I've just seen that the problem seems not to be with the query but with my mapping after the query.
Equivalent between Eloquent and pure MySQL query
Hello,
I have an eloquent query which don't really work fine.
And I have the pure MySQL query which works as I want.
Even I have a distinct() method, for the product which have 2 units, only one unit is shown.
$products = DB::table('products')
->join('ingredients', 'ingredients.product_id', '=', 'products.id')
->join('units', 'units.id', '=', 'ingredients.unit_id')
->join('recipes', 'recipes.id', '=', 'ingredients.recipe_id')
->join('meals', 'meals.recipe_id', '=', 'recipes.id')
->groupByRaw('products.id, units.shortname')
->orderBy('products.name')
->distinct()
->selectRaw('products.id as id, sum(ingredients.quantity) as quantity, units.shortname as shortname')
->get()
->mapWithKeys(function ($item, $key) {
return [
$item->id => [
'quantity' => $item->quantity,
'shortname' => $item->shortname,
]
];
});
Here it works fine.
select distinct
products.id as id,
sum(ingredients.quantity) as quantity,
units.shortname as shortname
from
products
inner join ingredients on ingredients.product_id = products.id
inner join units on units.id = ingredients.unit_id
inner join recipes on recipes.id = ingredients.recipe_id
inner join meals on meals.recipe_id = recipes.id
group by products.id, units.shortname
order by products.name asc
Here is an example of what I'd like to retrieve.
// What I get with the pure MySQL query
29, 5, kg
29, 350, g
29, 2, L
// What I get with the query builder
29, 2, L // => what I retrieve now with the query builder
The solution is perhaps to query with pure MySQL language. But how is it possible to run this query with Laravel ? And why doesn't the query builder give the same result ?
If you can help me ;) ... Thank you ;).
V
@vincent15000 You can store only one product_id (with same value) per user in that table. So you can't store data like this
29, 5, kg
29, 350, g
29, 2, L
where product_id is 29.
Please or to participate in this conversation.