简体   繁体   English

如何在Laravel中获得销售订单清单(交易)?

[英]How to get sale order list (transaction) in Laravel?

I have two database tables, 'product' and 'transactions' as be low 我有两个数据库表,“ product”和“ transactions”都很低

**Product.php**

product_id   product_name
--------------------------
1           |      A
2           |      B
3           |      C

**Transactions.php**

transaction_id       product_id
--------------------------------
1                |       1
2                |       1
3                |       1
4                |       3
5                |       2
6                |       3

From transaction table. 从交易表。 So the sale order (best sale) is [ACB]. 因此,销售订单(最佳销售)为[ACB]。 I tried something like below but not work. 我尝试了以下类似的方法,但是没有用。

$saleTtransaction = SaleTransaction::select('product_id', DB::raw('count(*) as total'))->groupBy('product_id')->get();

Appreciated for all comments, thanks. 感谢所有评论,谢谢。

Here is the raw query you probably want to use: 这是您可能要使用的原始查询:

SELECT
    p.product_name,
    COUNT(t.product_id) AS total
FROM products p
LEFT JOIN transactions t
    ON p.product_id = t.product_id
GROUP BY
    p.product_name
ORDER BY
    total DESC;

Here is the Laravel code for the above: 这是上面的Laravel代码:

$saleTtransaction = DB::table("products p")
    ->select("p.product_name",
             DB::raw('COUNT(t.product_id) AS total'))
    ->join("transactions t", "p.product_id", "=", "t.product_id")
    ->groupBy("p.product_name")
    ->orderBy('total', 'desc')
    ->get();

This assumes that each product always has a unique name. 假设每个产品始终具有唯一的名称。 If not, then technically we should aggregate both by the product name and id. 如果不是,那么从技术上讲,我们应该同时按产品名称和ID进行汇总。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM