Laravel SQL查询很难

时间:2014-06-02 21:40:16

标签: php sql laravel-4

我无法将下面的SQL查询“翻译”到Laravel,我怎么能做到这一点?

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);

我试过这个(返回错误):

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')]);

这个(返回空):

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)');

任何人都可以帮助我?

2 个答案:

答案 0 :(得分:0)

快速检查他们的文档,看起来您希望将整个查询作为原始表达式运行。

http://laravel.com/docs/queries#raw-expressions

HTH

答案 1 :(得分:0)

如果你想运行原始查询(对于像这样的复杂查询,我会坚持使用原始SQL,因为我对此感觉更舒服),你需要做的是:

$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使用DB::select()方法。

DB::raw()用于将较大查询表达式的 part 标记为原始SQL。有关详细信息,请参阅http://laravel.com/docs/queries#raw-expressions。实例