Laravel 5 Multi Select不工作

时间:2016-05-17 22:22:23

标签: php laravel laravel-4 laravel-5

我需要帮助在laravel 5中设置这一个查询。

这是我的表格示例......:

表名: mytable

 user_id  cost   status     created_at 
--------------------------------------
   1      10     Pending   2016-04-21 04:51:01
   1      20     Pending   2016-04-22 04:51:01
   1      100    Approved  2016-04-25 04:51:01 
   1      45     Pending   2016-04-28 04:51:01
   1      60     Approved  2016-05-01 04:51:01
   1      60     Approved  2016-05-01 04:51:01
   1      160    Approved  2016-05-03 04:51:01
   1      360     Pending   2016-05-05 04:51:01
   1      260     Approved  2016-05-12 04:51:01
   1      210     Pending   2016-05-21 04:51:01

基本上我需要Laravel中的一个SQL语句,它会输出类似这样的内容或者按用户关闭,因为我可能有不同的用户ID

           Totalpending    Totalapproved  TotalCost

April/2016    3               1            ( add cost for April)
May/2016      1               4             ( add all cost for May)  

到目前为止,我有这个代码,但如何在一个查询中完成所有操作?

$query = DB::table('my_table')->select(DB::raw('MONTH(created_at) as m, YEAR(created_at) as y'), DB::raw('count(*) as pp'))->where('user_id' ,Auth::id())->where('status','Pending')
  ->groupBy('created_at')
  ->get();  

var_dump($query);

但是这个输出只是等待如下:...

 array(1) {
  [0]=>
   object(stdClass)#321 (3) {
     ["m"]=>
      string(1) "4"
      ["y"]=>
      string(4) "2016"
      ["pp"]=>
      string(1) "3"
      }
   }

或者我可以有这样的输出: 在哪里" pp" >总待定," aa" >总批准," cc" >总费用

 array(1) {
  [0]=>
   object(stdClass)#321 (3) {
     ["m"]=>
      string(1) "4"
      ["y"]=>
      string(4) "2016"
      ["pp"]=>
      string(1) "3"
      ["aa"]=>
      string(1) "1"
      ["cc"]=>
      string(1) "175"
      }
   }

如何显示其他人的批准和总费用?

1 个答案:

答案 0 :(得分:0)

如果您仅使用SQL实现此功能,那么下面的内容可以帮助您。

SELECT CONCAT_WS('/', MONTHNAME(`created_at`), YEAR(`created_at`)) AS `Datum`,
  SUM(CASE WHEN `status` = 'Pending' THEN 1 ELSE 0 END) AS `TotalPending`,
  SUM(CASE WHEN `status` = 'Approved' THEN 1 ELSE 0 END) AS `TotalApproved`,
  SUM(`cost`) AS `TotalCost`
FROM `mytable`
GROUP BY `Datum`
ORDER BY `Datum` DESC;

但是由于您使用的是Laravel的查询构建器,我想它可以移植到下面的那个。

$query = DB::table('mytable')->select(
    DB::raw(
        'CONCAT_WS(\'/\', MONTHNAME(created_at), YEAR(created_at)) as Datum,
        SUM(CASE WHEN status = \'Pending\' THEN 1 ELSE 0 END) AS TotalPending,
        SUM(CASE WHEN status = \'Approved\' THEN 1 ELSE 0 END) AS TotalApproved,
        SUM(cost) as TotalCost'
    )
)->where('user_id', Auth::id())->groupBy('Datum')->orderBy('Datum', 'desc')->get();

Demo