Ich erhalte diesen Fehler in DataTables: DataTables-Warnung: Tabellen-ID=DataTables_Table_0 – Ausnahmemeldung:
Es wird versucht, die Nulleigenschaft „name“ zu lesen.
Obwohl jede position_id eine ID aus der Positionstabelle hat, sollte sie daher nicht leer sein. Wenn jemand helfen möchte, wäre ich dankbar. Mein Modell:
public function position() { return $this->belongsTo(Position::class); }
Mein Controller:
class EmployeeController extends Controller { public function index(Request $request) { if ($request->ajax()) { $data = Employee::with('position')->select('id','name','email')->get(); return Datatables::of($data)->addIndexColumn() ->addColumn('position', function (Employee $employee) { return $employee->position->name; })->addColumn('action', function($data){ $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm"> <i class="bi bi-pencil-square"></i>Edit</button>'; $button .= ' <button type="button" name="edit" id="'.$data->id.'" class="delete btn btn-danger btn-sm"> <i class="bi bi-backspace-reverse-fill"></i> Delete</button>'; return $button; }) ->make(true); } return view('admin.employees.index'); } }
Skript:
$(document).ready(function() { var table = $('.user_datatable').DataTable({ processing: true, serverSide: true, ajax: "{{ route('admin.employees.index') }}", columns: [ {data: 'id', name: 'id'}, {data: 'name', name: 'name'}, {data: 'email', name: 'email'}, {data: 'position', name: 'position.name'}, {data: 'action', name: 'action', orderable: false, searchable: false}, ] });
Migrieren:
public function up() { Schema::create('employees', function (Blueprint $table) { $table->id(); $table->string('name'); $table->foreignId('position_id')->nullable(); $table->string('phone_number'); $table->date('recruitment_date'); $table->string('email')->unique(); $table->string('image_path')->nullable(); $table->string('payment'); $table->timestamps(); $table->string('admin_created_id')->nullable(); $table->string('admin_updated_id')->nullable(); }); }
此错误意味着当 Datatable 尝试从
$data
获取数据时,没有集合或数组将其定位在get()
方法内所以,当您查看
$raw
时,上面的返回没有位置或属性从那时起,我们将把控制器更改为这样
如果不起作用,您可以尝试更改数据库查询 但为此我需要转储 $data 您可以在浏览器中的 Inspect 元素的 Network 部分中看到结果
dd($data);
问题是因为选择。似乎如果你要使用关系,你必须在选择中添加外键(在我的例子中是“position_id”),或者完全删除它并只使用 get 。感谢所有在评论中提供帮助的人。