我在搜索联接表字段中的记录时遇到问题。我需要搜索包括联接表列在内的所有列。
这是我的“所有国家/地区”的控制器功能:
public function allStates()
{
$states = State::select(['id', 'country_id', 'state_type', 'state_code', 'state_name', 'status'])->orderBy('country_id','Asc');
return Datatables::of($states)
->addColumn('checkes', function ($states) {
$data = $states;
return view('partials.datatable.table_first_column_checkbox', compact('data'))->render();
})
->editColumn('country_id', function ($states) {
return $states->country ? $states->country->country_name : "N/A";
})
->editColumn('status', function ($states) {
$data = $states;
$statusChangeRoute = route('state.change.status');
return view('partials.datatable.status-switch', compact('data','statusChangeRoute'))->render();
})
->addColumn('action', function ($states) {
$editRoute = route('states.edit', $states->id);
$viewRoute = route('states.show', $states->id);
$controlKeyword = 'state';
return view('partials.datatable.table_edit_delete_action', compact('editRoute','viewRoute','controlKeyword'))->render();
})
->addColumn('DT_RowId', function ($states) {
return "tr_" . $states->id;
})
->rawColumns(['checkes', 'status', 'action'])
->make(true);
}
在此功能中,我刚刚编辑了country_id
列并返回了$states->country->country_name
这是我的js函数:
<script type="text/javascript">
$(document).ready(function () {
table = $('#tblState').DataTable({
processing: true,
serverSide: true,
pageLength: 10,
ajax: {
url: "{{ route('admin.states.list') }}",
type: "POST",
data: {_token: "{{csrf_token()}}"}
},
columns: [
{data: 'checkes', name: 'checkes', orderable: false, searchable: false},
{data: 'country_id', name: 'country_id'},
{data: 'state_type', name: 'state_type'},
{data: 'state_code', name: 'state_code'},
{data: 'state_name', name: 'state_name'},
{data: 'status', name: 'status'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
"bStateSave": true,
initComplete: function (settings, json) {
// called on first time initialization
},
drawCallback: function (settings) {
// called on every server request
// below function is compulsory put here with table id param
initDTCheckBox('tblState');
}
});
});
</script>
这是我的查看屏幕
答案 0 :(得分:2)
您可以直接在查询中使用:
$states = State::select(['id', 'country_id', 'state_type',
'state_code', 'state_name', 'status'])
->orderBy('country_id', 'Asc')
->with('country');
然后直接在您的JS中使用:
{data: 'country.country_name', name: 'country.country_name'},
addColumn
仅影响列的视图,但不影响查询。因此,当您要订购或在数据表中搜索时,插件找不到值,您必须在查询中包含它