Cara Menggunakan Laravel Pagination dengan Distinct

Masalah: ketika menggunakan distinct pada fungsi paginate, ternyata hasil querynya sudah benar hanya tampil 2 data (fungsi distinct berhasil), namun total data/count-nya masih 12 (tanpa distinct).

$data = InputTindakan::join("tindakan AS t", "input_tindakan.tindakan_id", "t.id")
        ->whereRaw("rawat_jalan_id=?", [$kunjungan_id])
        ->selectRaw("tindakan_id AS id,t.nama as text")
        ->orderByRaw("t.nama")
        ->distinct()
        ->paginate(request('per_page', 10));

Solusi: ganti distinct() dengan groupBy()

$data = InputTindakan::join("tindakan AS t", "input_tindakan.tindakan_id", "t.id")
        ->whereRaw("rawat_jalan_id=?", [$kunjungan_id])
        ->selectRaw("tindakan_id AS id,t.nama as text")
        ->orderByRaw("t.nama")
        ->groupBy("tindakan_id")
        ->paginate(request('per_page', 10));

Semoga bermanfaat. Tetap Sehat, Tetap Semangat, Tetap dalam Perdjoeangan!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.