将select max case转换为laravel query builder

时间:2016-12-08 13:34:12

标签: php mysql laravel laravel-5.2

如何将此选择查询转换为laravel查询构建器?

select
wi.id,
wi.nama,
max(case when dw.kode_kriteria like '2k%' then ks.nama_kriteria_sub else '' end) as country,
max(case when dw.kode_kriteria like '3k%' then ks.nama_kriteria_sub else '' end) as gender,
max(case when dw.kode_kriteria like '4k%' then ks.nama_kriteria_sub else '' end) as purpose,
group_concat(distinct wo.id_objek) as visit_to

初​​始

wi => ta_wisatawan
dw => ta_k_detail_wisatawan
ks => ta_kriteria_sub
wo => ta_k_wisata_objek

在此查询构建器中转换

$show_wi = DB::table('ta_wisatawan')
->leftJoin('ta_k_detail_wisatawan', 'ta_k_detail_wisatawan.id_wisatawan', '=', 'ta_wisatawan.id')
->leftJoin('ta_kriteria_sub', 'ta_kriteria_sub.kode', '=', 'ta_k_detail_wisatawan.kode_kriteria')
->leftJoin('ta_k_wisata_objek', 'ta_k_wisata_objek.id_wisatawan', '=', 'ta_wisatawan.id')
->select(.....)

我已经为此选择做了几种方法,但它没有用。

2 个答案:

答案 0 :(得分:0)

您可以使用DB::raw()与querybuilder一起使用,如下所示:

->select(DB::raw([
    "wi.id",
    "wi.nama",
    "max(case when dw.kode_kriteria like '2k%' then ks.nama_kriteria_sub else '' end) as country",
    "max(case when dw.kode_kriteria like '3k%' then ks.nama_kriteria_sub else '' end) as gender",
    "max(case when dw.kode_kriteria like '4k%' then ks.nama_kriteria_sub else '' end) as purpose",
]))->get();
  

详细了解Laravel's Raw Expressions

希望这有帮助!

答案 1 :(得分:0)

DB::raw接受字符串,请尝试以下查询:

->select(
    DB::raw(
        "wi.id, wi.nama, max(case when dw.kode_kriteria like '2k%' then ks.nama_kriteria_sub else '' end) as country, max(case when dw.kode_kriteria like '3k%' then ks.nama_kriteria_sub else '' end) as gender, max(case when dw.kode_kriteria like '4k%' then ks.nama_kriteria_sub else '' end) as purpose"
    )
)
->get();