有谁知道如何使“Tanggal Dibuat”(created_at)列按日期排序?目前当我点击它时。我认为日期没有显示正确的顺序,因为created_at被读取为字符串,而不是日期。我正在使用 Laravel 8 和 Yajra 数据表。这是我的数据表文件夹中的 UsersDatatables 代码
public function dataTable($query)
{
return datatables()
->eloquent($query)->addIndexColumn()
->editColumn('created_at', function($data) {
$formatedDate = Carbon::createFromFormat('Y-m-d H:i:s', $data->created_at)->format('d/m/Y'); return $formatedDate; })
->editColumn('updated_at', function($data) {
$formatedDate = Carbon::createFromFormat('Y-m-d H:i:s', $data->updated_at)->format('d/m/Y'); return $formatedDate; })
->editColumn('is_active', function ($item) {
return $item->is_active == 1 ? 'AKTIF' : 'NON-AKTIF';
})
->addColumn('action', function($item) {
return '
<div class="btn-group">
<div class="dropdown">
<button class="btn btn-primary btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Aksi
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<li>
<a class="dropdown-item" href="'. route('user.edit', $item->id) .'">
Ubah
</a>
</li>
<li>
<a href="'. route('user.delete', $item->id) .'" class="dropdown-item text-danger" data-confirm-delete="true">
Delete
</a>
</li>
</ul>
</div>
</div>
';
});
}
public function query(User $model)
{
return $model::with('role');
}
public function html()
{
return $this->builder()
->scrollY(725)
->scrollCollapse(false)
->setTableId('users-table')
->serverSide(false)
->languagePaginateNext('→')
->languagePaginatePrevious('←')
->columns($this->getColumns())
->minifiedAjax()
->orderBy(0, 'asc');
}
protected function getColumns()
{
return [
Column::make('DT_RowIndex')
->title('No')
->addClass('text-center')
->orderable(false),
Column::make('name')
->addClass('text-center')
->title('Nama'),
Column::make('role.name')
->addClass('text-center')
->title('Role'),
Column::make('is_active')
->addClass('text-center')
->title('Status'),
Column::make('created_at')
->addClass('text-center')
->title('Tanggal Dibuat'),
Column::computed('action')
->addClass('text-center')
->title('Opsi')
->exportable(false)
->printable(false)
->addClass('text-center')
];
}
protected function filename()
{
return 'User_' . date('YmdHis');
}
Yajra Datatables 在前端使用 jquery 数据表。从这里可以看到,您可以通过现有功能进行订购:See
适合您的函数可能是
orderData()
:https://datatables.net/reference/option/columns.orderData
这样做:
public function html()
{
return $this->builder()
->scrollY(725)
->scrollCollapse(false)
->setTableId('users-table')
->serverSide(false)
->languagePaginateNext('→')
->languagePaginatePrevious('←')
->columns($this->getColumns())
->minifiedAjax()
->orderBy(4, 'desc') // Order by the 4th column (created_at) in descending order
->orderData([4, 0]); // Specify that the 4th column (created_at) should be treated as date for ordering
}
试试这个
public function query(User $model)
{
return $model::with('role')->orderBy('created_at', 'asc');
}