Home > Mobile >  raw query join left with select to laravel 8 query
raw query join left with select to laravel 8 query

Time:06-29

i'm using raw query on my laravel function, and i wanna make it into laravel query builder, but i really have no idea how to do it, i've read laravel documentary about advanced join clause or subquery joins, but still cant figuring it out how to convert it

raw query :

$buku = DB::select(
        DB::raw('
        SELECT buku.*, kategory, tag
        FROM buku
        LEFT JOIN kategori_buku ON buku.id_kategori = kategori_buku.id
        LEFT JOIN detail_buku_tag ON buku.id = detail_buku_tag.id_buku
        LEFT JOIN (SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku ON tag_buku.id = detail_buku_tag.id_tag
        GROUP BY buku.id')
    );

CodePudding user response:

try this

$buku = \DB::table('buku')
->select([
    'buku.*',
    'kategory.*',
    'tag.*'
])
->leftJoin('kategori_buku', 'kategori_buku.id', '=', 'buku.id_kategori')
->leftJoin('detail_buku_tag', 'detail_buku_tag.id_buku', '=', 'buku.id')
->leftJoin(DB::raw('SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku ON tag_buku.id = detail_buku_tag.id_tag GROUP BY buku.id'))
->get();

CodePudding user response:

there some sql chaining issue. @Ramiz Kongulov forget to split group by clause try this.

$buku = \DB::table('buku')
    ->select(['buku.*','kategory.*', 'tag.*'])
    ->leftJoin('kategori_buku', 'kategori_buku.id', '=', 'buku.id_kategori')
    ->leftJoin('detail_buku_tag', 'detail_buku_tag.id_buku', '=', 'buku.id')
    ->leftJoin(\DB::raw('(SELECT tag_buku.id, GROUP_CONCAT(tag) AS tag FROM tag_buku) AS tag_buku'),
        'tag_buku.id', '=', 'detail_buku_tag.id_tag')
    ->groupBy('buku.id')
    ->get();
  • Related