I have 6 columns in my datatable. One of them is the ID of the tickets table.
When I sort the columns in the datatable it replaces the ID with the ID of the sorted column table.
For example, If I sort the client column then it will replace all the ticket ID's with the client ID's.
What am I doing wrong?
$model = Ticket::with('client', 'location', 'status', 'priority');
if($request->ajax()) {
return Datatables::eloquent($model)
->addColumn('client', function (Ticket $ticket) {
return $ticket->client->name;
})
->addColumn('location', function (Ticket $ticket) {
if($ticket->location) {
return $ticket->location->location;
} else {
return "";
}
})
->addColumn('priority', function (Ticket $ticket) {
if($ticket->priority) {
return $ticket->priority->name;
} else {
return "";
}
})
->addColumn('status', function (Ticket $ticket) {
if($ticket->status) {
return $ticket->status->name;
} else {
return "";
}
})
->make(true);
}
"columns": [
//This column gets overridden
{ "data": "id", "name": "id",
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
console.log(oData);
$(nTd).html("<a href='/tickets/"+oData.id+"'>"+oData.id+"</a>");
}
},
{ "data": "client", "name": "client.name",
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
if(oData.client) {
$(nTd).html("<a href='/clients/"+oData.client_id+"'>"+oData.client+"</a>");
}
}
},
{ "data": "location", "name": "location.location", "defaultContent": "" },
{ "data": "priority", "name": "priority.name" },
{ "data": "status", "name": "status.name" },
{ "data": "date", "name": "date" },
],
You need to add select('tickets.*')on your query to avoid this issue as documented here.
$model = Ticket::with('client', 'location', 'status', 'priority')->select('tickets.*');
Thanks!
Most helpful comment
You need to add
select('tickets.*')on your query to avoid this issue as documented here.