gpt4 book ai didi

php - Laravel 数据表按关系列排序不起作用

转载 作者:行者123 更新时间:2023-12-04 11:21:28 26 4
gpt4 key购买 nike

我有一个 User谁可以分配到多个Company .我正在尝试使用 Laravel Datatables 和 jQuery Datatables 呈现表格。它呈现得很好,当单击表标题中的订单图标时,它会按该列对数据进行排序,除了它不适用于关系列 company_name .
这是我在 Controller 中的代码:

$users = User::with(['roles','companies'])
->where('users.id', '!=', Auth::id())
->whereHas('roles', function($q){$q->whereId(Role::ROLE_6);});

...
return Datatables::of($users)
->editColumn('company', function (User $user) {
return $user->hasCompanies()? $user->companies->first()->company_name : trans('lang.company.not_assigned');
})
->orderColumn('company', 'company')
->make(true);

这是我用于数据表的 javascript:
otable = $('#datatable_fixed').DataTable({
"ajax": {
url: 'users/datatable',
type: 'POST',
},
"pageLength": 15,
"processing": true,
"stateSave": true,
"serverSide": true,
"bDestroy": true,
columns: [
{data: 'first_name', name: 'first_name'},
{data: 'last_name', name: 'last_name'},
{data: 'company', name: 'company.company_name'},
{data: 'email', name: 'email'},
{data: 'status', name: 'status'},
],
dom: 'Bfrtip',
searching: false,
"order": [[0, 'asc']],
"autoWidth": true,
});

最佳答案

我有一张 table 叫 ridesdrivers 有多重关系, customers , vehicles , 和 companies .我需要一列,其中包含可排序和可搜索的两个关系表列的串联值。
此查询为我完成上述工作

$rides = Ride::select(['rides.*', DB::raw('CONCAT(drivers.code," - ",drivers.name) AS driver')])
->with(['drivers','customers','vehicles','companies'])
->join('drivers','rides.driver_id','=', 'drivers.id');
在此之后,我将以下代码添加到加载数据表数据的 ajax 方法中。
var table = $('#myTable').DataTable({
"processing":true,
"serverSide":true,
"ajax": "{{route('ajax.view.rides')}}",
"columns": [
{data: 'driver', name: 'driver', searchable:false},
{data: 'drivers.code', name:'drivers.code', searchable: true, sortable : true, visible:false},
{data: 'drivers.name', name:'drivers.name', searchable: true, sortable : true, visible:false},

],
responsive:true,
order:[0,'desc']
});
我们在查询中添加的连接列使排序成为可能
{data: 'driver', name: 'driver', searchable:false},
此列定义将使两列的搜索成为可能
{data: 'drivers.code', name:'drivers.code', searchable: true, sortable : true, visible:false},
{data: 'drivers.name', name:'drivers.name', searchable: true, sortable : true, visible:false},
现在您需要添加两个额外的 <th> HTML 表线程元素内的标签。
<thead>
<tr>
<th>Driver</th> <!-- this one will display the concatenated column -->
<th>Driver</th> <!-- this one is for the hidden hidden column that enables the search on one column -->
<th>Driver</th> <!-- this one is for the hidden hidden column that enables the search on one column -->
</tr>
</thead>

关于php - Laravel 数据表按关系列排序不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com