我只是想获取每个客户 ID 的最新日期/时间,但 orderBy 代码似乎不起作用。我先尝试使用,但我不断收到数据表错误 7。
控制器
public function refresh(){
$cash_advance = DB::table('cash_advance')
->join('customer', 'customer.id', '=', 'cash_advance.customer_id')
->select('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.created_at', 'cash_advance.balance')
->groupBy('cash_advance.customer_id')
->orderBy('cash_advance.created_at', 'desc')
->get();
return \DataTables::of($cash_advance)
->addColumn('action', function($cash_advance){
return '<button class="btn btn-xs btn-info" id="'.$cash_advance->customer_id.'"><i class="material-icons" style="width: 25px;">visibility</i></button>';//info/visibility
})
->make(true);
}
数据表
var cash_advancetable = $('#cash_advancetable').DataTable({
dom: 'Bfrtip',
buttons: [
],
processing: true,
serverSide: true,
ajax: "{{ route('refresh_cashadvance') }}",
columns: [
{render: function(data, type, full, meta){
return full.fname +" "+full.mname+" "+full.lname;
}},
{data: 'amount', name: 'amount'},
{data: 'created_at', name: 'created_at'},
{data: 'balance', name: 'balance'},
{data: "action", orderable:false,searchable:false}
]
});
要获取最新日期,只需使用 max 聚合器:
max('cash_advance.created_at')
。
但无论如何,在上面的 groupBy 语句中,您应该选择所有与客户相关的功能 像这样:
DB::table('cash_advance')
->join('customer', 'customer.id', '=', 'cash_advance.customer_id')
->select('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance', DB::raw('MAX( cash_advance.created_at)'))
->groupBy('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance',)
->orderBy('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance', 'desc')
->get();
对于 id 缩写,请添加 $("#dataTable").DataTable({order:[[0,"desc"]]});