我在 DataTables 中收到此错误:DataTables 警告:表 id=DataTables_Table_0 - 异常消息:
尝试读取 null 属性“name”。
虽然每个position_id都有位置表中的id,所以它不应该为空。如果有人愿意提供帮助,我将不胜感激。我的模型:
public function position()
{
return $this->belongsTo(Position::class);
}
我的控制器:
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');
}
}
脚本:
$(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},
]
});
迁移:
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();
});
} Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
此错误意味着当 Datatable 尝试从
$data获取数据时,没有集合或数组将其定位在get()方法内{ collection[0]{ 0 => 'Models/Employees'[0], 1 => 'Models/Employees'[1] }所以,当您查看
$raw时,上面的返回没有位置或属性从那时起,我们将把控制器更改为这样
public function index(Request $request) { if ($request->ajax()) { $data = Employee::query()->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 .= ' '; return $button; }) ->make(true); } return view('admin.employees.index'); }如果不起作用,您可以尝试更改数据库查询 但为此我需要转储 $data 您可以在浏览器中的 Inspect 元素的 Network 部分中看到结果
dd($data);问题是因为选择。似乎如果你要使用关系,你必须在选择中添加外键(在我的例子中是“position_id”),或者完全删除它并只使用 get 。感谢所有在评论中提供帮助的人。