如何在Laravel查询构建器中使用联合查询编写RIGHT JOIN

时间:2018-07-22 12:21:31

标签: laravel laravel-5 eloquent

我是laravel的新手,我有如下查询,想使用laravel构建器进行查询,但是不幸的是,我很困惑如何使用laravel构建器查询或雄辩地编写它。

SELECT
  idMonth,
  MONTHNAME(STR_TO_DATE(idMonth, '%m')) as m,
  IFNULL(count(id), 0) as total
FROM kontrak_penjualans
RIGHT JOIN (
  SELECT 1 as idMonth
  UNION SELECT 2 as idMonth
  UNION SELECT 3 as idMonth
  UNION SELECT 4 as idMonth
  UNION SELECT 5 as idMonth
  UNION SELECT 6 as idMonth
  UNION SELECT 7 as idMonth
  UNION SELECT 8 as idMonth
  UNION SELECT 9 as idMonth
  UNION SELECT 10 as idMonth
  UNION SELECT 11 as idMonth
  UNION SELECT 12 as idMonth
) as Month
ON Month.idMonth = month(`tgl_kontrak`)
GROUP BY Month.idMonth

如何用雄辩的语言或在laravel中编写查询?特别是对于RIGHT JOIN。 :(

我已经尝试过这种方法,但是如果我在mysql控制台中查询,代码MONTHNAME(STR_TO_DATE(idMonth, "%m"))返回null。

DB::table('kontrak_penjualans')
     ->select('idMonth',DB::raw('MONTHNAME(STR_TO_DATE(idMonth, "%m")) as m,
      IFNULL(count(id), 0) as total'))
     ->rightJoin(
        DB::raw("(SELECT 1 as idMonth
          UNION SELECT 2 as idMonth
          UNION SELECT 3 as idMonth
          UNION SELECT 4 as idMonth
          UNION SELECT 5 as idMonth
          UNION SELECT 6 as idMonth
          UNION SELECT 7 as idMonth
          UNION SELECT 8 as idMonth
          UNION SELECT 9 as idMonth
          UNION SELECT 10 as idMonth
          UNION SELECT 11 as idMonth
          UNION SELECT 12 as idMonth) as Month"), 'Month.idMonth' ,'=', DB::raw('month(tgl_kontrak)')
    )
     ->groupBy('Month.idMonth')->get();

0 个答案:

没有答案