添加闭包以选择原始查询(总和)

时间:2020-08-20 19:36:16

标签: laravel query-builder

同一张表中的选择和有很多不同的组合,但是查询的位置略有不同。

foreach ($transactionTypes as $type) {

   switch($type) {
      case 'Fuel':
          $values = \DB::table("transactions")
                 ->select(\DB::raw("user_id, SUM(fuel_charge) as fuel_charges"))
                 ->whereIn('type', ["Charge", "Refund"])
                 ->whereIn('user_id', $userIdsToBeUsed)
                 ->whereDate('created_at', '>=', $fromDate->toDateString())
                 ->whereDate('created_at', '<=', $toDate->toDateString())
                 ->groupBy('user_id')
                 ->get();
      break;

      case 'Commission':
           $userIdsToBeUsed = $userIds->merge($tier3Ids);      

           $values = \DB::table("transactions")
                 ->select(\DB::raw("user_id, SUM(commission_charge) as commission_charges"))
                 ->whereIn('user_id', $userIdsToBeUsed)
                 ->whereDate('created_at', '>=', $fromDate->toDateString())
                 ->whereDate('created_at', '<=', $toDate->toDateString())
                 ->groupBy('user_id')
                 ->get();

           break;
   }
}

如您所见,它们略有不同,循环中有十几种情况;但是使用这种方法,我需要对同一张表进行一打查询。

我想问的是,有没有办法将它们组合成一个查询?

类似的东西:

$values = \DB::table("transactions")
            ->select(
              [ 
                 \DB::raw("user_id, SUM(fuel_charge) as fuel_charges") => function($q) {
                   // $q->where(...)
                 }
              ],
              [
                 \DB::raw("user_id, SUM(commission_charge) as commission_charges") => function($q) {
                    // $q->where(...);
                 }
              ])
            ->get()

1 个答案:

答案 0 :(得分:-1)

快速思考。您可以说这是一个非常简洁的技巧:

import graphene

class A(graphene.Interface):
    field_y = graphene.Int()
    field_z = graphene.String()

class B(graphene.ObjectType):
    class Meta:
        abstract = True
    field_y = graphene.Int()
    field_z = graphene.String()

class ChildA(graphene.ObjectType):
    class Meta:
        interfaces = (A,)

    field_x = graphene.Float()

class ChildB(B):
    field_x = graphene.Float()

我只在查询中使用$userIdsToBeUsed = $userIds->merge($tier3Ids); foreach ($transactionTypes as $type) { $values = \DB::table("transactions") ->select(\DB::raw("user_id, SUM(" . strtolower($type) . "_charge) as " . strtolower($type) . "_charges")) ->whereIn('type', ["Charge", "Refund"]) ->whereIn('user_id', $userIdsToBeUsed) ->whereDate('created_at', '>=', $fromDate->toDateString()) ->whereDate('created_at', '<=', $toDate->toDateString()) ->groupBy('user_id') ->get(); } 的小写字母

相关问题