Laravel Eloquent relation DataTable

56 Views Asked by At
if (request()->ajax()) {
            $query = BangunanKategori::with('bidang');
            return DataTables::eloquent($query)
                ->addColumn('nama_bidang', function ($item) {
                    return $item->bidang->nama;
                })
                ->addColumn('kode_bidang', function ($item) {
                    return $item->bidang->kode;
                })
                ->toJson();
        }

I have a problem displaying the DataTable code above because the relation table has the same column names. If the data is sorted based on kode_bidang and nama_bidang the data will be duplicated from the bidang relation table.

Please help me fix this. I have tried various methods, but the data displayed remains duplicate if ordered via these two columns.

1

There are 1 best solutions below

0
Karl Hill On

You can use Laravel's groupBy and select methods to ensure that only distinct bidang records are retrieved from the database.

if (request()->ajax()) {
    $query = BangunanKategori::with('bidang')
        ->select('bangunan_kategori.*', 'bidang.nama as nama_bidang',
        'bidang.kode as kode_bidang')
        ->groupBy('bangunan_kategori.id'); // Assuming 'id' is the primary key of the BangunanKategori table

    return DataTables::eloquent($query)
        ->toJson();
}