我正在使用Yajra数据表。我想显示数据并使用总统姓名过滤数据 我有3张桌子
1- Planes = id, title, description.
2- presidents = id, P_name.
3- Plane_president = plane_id , president_id
平面模型:
public function president()
{
return $this->belongsToMany(President::class);
}
主席模型:
public function planes()
{
return $this->belongsToMany(Plane::class);
}
我的控制器:
public function index(Request $request)
{
if ($request->ajax()) {
$query = Plane::with('presidents')->selectRaw('distinct planes.*');
return $this->dataTable
->eloquent($query)
->addColumn('P_name', function (Plane $plane) {
return $plane->presidents->map(function($president) {
return str_limit($president->P_name);
})->implode('<br>');
})
->make(true);
}
return view('planes.index');
}
js代码:
<script type="text/javascript">
$('#search').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route("plane.index") }}',
columns: [
{data: 'id', name: 'id'},
{data: 'main_point', name: 'main_point'},
{data: 'presidents[, ].P_name', name: 'president'},
]
});
</script>
我有这个错误
message "Undefined property: App\\Http\\Controllers\\PlaneController::$dataTable"
如何解决此错误?
答案 0 :(得分:1)
您需要按如下所述通过它。
return datatables()->eloquent($query);
请检查document。并建议总统显示姓名。
implode(', ', $plane->presidents->pluck('P_name')->toArray())
答案 1 :(得分:1)
使用DataTables::
来制作datatable
,而您想念的->rawColumns(['p_name'])
是我添加的
if ($request->ajax()) {
$plane = Plane::with('presidents')->selectRaw('distinct planes.*')->get();
return \DataTables::of($plane)
->addColumn('p_name', function ($plane) {
return implode(', ', $plane->presidents->pluck('P_name')->toArray());
})
->rawColumns(['p_name'])
->make(true);
}
在javascript中
<script type="text/javascript">
$('#search').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route("plane.index") }}',
columns: [
{data: 'id', name: 'id'},
{data: 'main_point', name: 'main_point'},
{data: 'p_name', name: 'p_name'}, // manipulate data of this column in server side here just echo like this
]
});
</script>