【问题标题】:How to count the orders of one product?如何计算一个产品的订单?
【发布时间】:2020-06-22 19:42:27
【问题描述】:

我有productsorders和第三个数据透视表product_order(product_id, order_id),我需要根据created_at统计产品的订单数

我的闭嘴:

public function product_chart(Product $product)
{
        $orders = $product->whereHas('orders', function ($query)  {
                    $query->whereMonth('created_at', '04');
                })->count();
    dd($orders);
}

输出给出了产品的数量:(

当然,我在名为 (orders) 的产品和名为 (products) 的订单中有关系

所以我需要根据order的created_at来统计产品的订单!

【问题讨论】:

    标签: laravel


    【解决方案1】:

    那是因为您在计算产品。

    你可以这样做:

    $ordersCount = $product->orders()->count();
    

    但是由于你应用了一些条件,你需要附加 where 子句:

    $ordersCount = $product->orders()->whereMonth('created_at', '04')->count();
    

    根据Laravel Documentation,还有一种更简单的方法:

    use Illuminate\Database\Eloquent\Builder;
    
    $posts = App\Post::withCount(['votes', 'comments' => function (Builder $query) {
        $query->where('content', 'like', 'foo%');
    }])->get();
    
    echo $posts[0]->votes_count;
    echo $posts[0]->comments_count;
    

    【讨论】:

    • 谢谢工作,但如果我需要计算这些订单中产品的总价格怎么办?请问这是什么想法?再次基于 created_at 像日或年
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多