php - Laravel - 从第三个关系开始计数

标签 php mysql laravel laravel-4 relationship

我有以下代码:

        $main = Main::with(['clients', 'events.orderitems' => function($query) {
        $query->whereIn('order_id', function($query) {
            $query->select('id')->from('orders')->where('orderPaid', 1)->orWhere('orderStatus', 3);
        });
    }])->where('id', $id)->first();

    foreach($main->events as $dates) {
        $all_paid = 0;
        $all_pending = 0;
        foreach($dates->orderitems as $item) {
            if($item->orderPaid == 1) {
                $all_paid = $all_paid + $item->quantity;
            }

        }
        $dates->orderscount = $all_paid;

        foreach($dates->orderitems as $item) {
            if($item->orderStatus == 3) {
                $all_pending = $all_pending + $item->quantity;
            }

        }
        $dates->pendingcount = $all_pending;

    }  

是否有一种 MYSQL 方法可以计算已付款订单和 SQL 中 orderStatus == 3 的订单?我想,我的做法太困惑了,而且对性能来说也不太好。

因此,“Main”有 n 个事件,其中有 n 个 orderItem。

我需要进入“主要”事件,所有包含所有 PAID 且 orderStatus == 3 项的事件。我怎样才能做到这一点?

更新 - 解决方案:

        foreach($main->events as $dates) {
        $dates->orderscount = OrderItems::where('events_id',$dates->id)->whereHas('orders', function($q) {
                $q->where('orderPaid', 1);
            })->sum('quantity');
        $dates->pendingcount = OrderItems::where('events_id',$dates->id)->whereHas('orders', function($q) {
                $q->where('orderStatus', 3);
            })->sum('quantity');
    }

最佳答案

Laravel 有一个 aggregate method就是这样做的。

与使用 first 的方式相同,仅获取查询的第一个结果,如下所示:

)->where('id', $id)->first();

要获取计数,您可以使用count()

 DB::table('orders')->where('orderPaid', 1)->orWhere('orderStatus', 3)->count();

如果您需要产品的 sum() 而不是标题中的 count,则可以在您的特定示例中使用:

  $total_quantity = DB::table('orders')->where('orderPaid', 1)->orWhere('orderStatus', 3)->sum('quantity');
<小时/>

更新:

如您的示例中所示,要获得这两个计数,您将 foreach 更改为类似于以下内容的内容:

foreach($main->events as $dates) {
    $all_paid = DB::table('orders')->where('order_id',$dates->id)->where('orderPaid', 1)->count();
    $all_pending = DB::table('orders')->where('order_id',$dates->id)->where('orderStatus', 3)->count();

    $dates->orderscount = $all_paid;
    $dates->pendingcount = $all_pending;

}  

关于php - Laravel - 从第三个关系开始计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26567930/

相关文章:

php - 无法使用 PHP 和 PDO 插入

php - 使用 PHP 在 session 中将两个数组合并在一起

php - Yii Framework 2.0 上传文件报错 finfo_file() : failed to open stream: No such file or directory

php - Laravel 5.8 如何获取职位 ID?

php - 在 Windows 上使用 Laravel 5.7 出现 500 服务器错误

php - Drupal 用户关系查询将获取 Count Common Friend

php - MYSQL 两个不同表查询相同字段

mysql - 组内的 SQL 组

mysql - Codeigniter - 输入后数组插入 mysql 数据库

mysql - Laravel - 在现有表上添加外键数据