在Laravel 5.8的查询中插入查询

时间:2019-04-09 09:24:51

标签: laravel-5

我在控制器上具有此功能以打印月度报告。该报告显示前几个月的余额,并显示特定月份股票的交易输入和输出单位。

我已经在本月尝试查询事务,但是无法将几个月前的余额查询插入一个表中。

public function p_report(Request $request) {
    $report = DB::table('unit as u')
    ->select('u.id','name_u',
        'price',
        DB::raw('sum(qty_in) vol_in'),
        DB::raw('sum(price*qty_in) qty_ins'),
        DB::raw('sum(qty_out) vol_out'),
        DB::raw('sum(price*qty_out) qty_outs'),
        DB::raw('sum(qty_in)-sum(qty_out) vol_end'),
        DB::raw('sum(price*qty_in)-sum(price*qty_out)qty_end')
        )
    ->leftJoin('transaction as t', 't.unit_id', '=', 'u.id')
    ->where('status',1)
    ->where('type_unit', '=' , $request->type_unit)
    ->whereMonth('date_transaction','=', $request->month)
    ->whereYear('date_transaction', '=' , $request->year)
    ->groupBy(['u.id','name_u','price'])
    ->orderBy('name_u')
    ->get();

    foreach ($report as $reports) {
        $balance = DB::table('unit as u')
       ->select(
          DB::raw('sum(price*qty_in)-sum(price*qty_out) qty_balance')
          )
       ->leftJoin('transaction as t', 't.unit_id', '=', 'u.id')
       ->where('u.id', '=' , $reports->id)
       ->whereMonth('date_transaction','<', $request->month)
       ->whereYear('date_transaction', '=' , $request->year)
       ->get();
        $reports->qty_balance = $balance;
     }

    return view ('report/p_report', compact('report','balance','reports'));
}

我可以将一个查询插入到另一个查询中成为单个表吗?我已经尝试过,但是这样的结果是,我希望qty_balance显示一个不在Collection内的值,如下所示:

    Collection {#247 ▼
  #items: array:3 [▼
    0 => {#245 ▼
      +"id": 3
      +"name_unit": "Folio"
      +"price": 40000
      +"vol_in": "81"
      +"qty_ins": "3240000"
      +"vol_out": "16"
      +"qty_outs": "640000"
      +"vol_end": "65"
      +"qty_end": "2600000"
      +"qty_balance": Collection {#262 ▶}
    }
    1 => {#246 ▼
      +"id": 5
      +"name_unit": "Pulpen"
      +"price": 50000
      +"vol_in": "100"
      +"qty_ins": "5000000"
      +"vol_out": "23"
      +"qty_outs": "1150000"
      +"vol_end": "77"
      +"qty_end": "3850000"
      +"qty_balance": Collection {#267 ▶}
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用:

我认为“融合”查询毫无意义。