Laravel SQL Query difficult
Question
I can't "translate" the SQL Query below to Laravel, how I can make this?
SELECT SUM(transactions.amount) AS total, products.name
FROM transactions, product_stock, product_catalog, products
WHERE transactions.id_product_stock = product_stock.id_prodct_stock
AND product_stock.id_product_catalog = product_catalog.id_product_catalog
AND product_catalog.id_product = products.id_produto
GROUP BY (products.name);
I tried this (returns error):
Transaction::join('product_stock', 'transactions.id_product_stock', '=', 'product.stock.id_product_stock')
->join('product_catalog', 'product_stock.id_product_catalog', '=', 'product_catalog.id_product_catalog')
->join('products', 'product_catalog.id_product', '=', 'products.id_product')
->groupBy('products.name')
->get([ DB::raw('SUM(transactions.amount) AS total'), DB::raw('products.name as name')]);
And this (returns empty):
DB::raw('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)');
Anyone can help me?
Solution
If you want to run the raw query (and for a complex query like this, I would stick with the raw SQL because I'm more comfortable with that), what you need to do is this:
$value = DB::select('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)'
);
Here's the documentation for use of the DB::select()
method.
DB::raw()
is used to mark part of a larger query expression as raw SQL. See http://laravel.com/docs/queries#raw-expressions for details & examples.
OTHER TIPS
quick checking their documentation it looks like you want to run your entire query as a raw expression.
http://laravel.com/docs/queries#raw-expressions
hth
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow