如何在 laravel 中显示与 yajra 数据表多对多关系的数据?

How to display data with yajra datatable many to many relationship in laravel?

我正在使用 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"

如何解决这个错误?

您需要按如下方式传递。

return datatables()->eloquent($query);

请检查document。对于显示总统的名字,我会建议。

implode(', ', $plane->presidents->pluck('P_name')->toArray())

使用 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>