我想从部门表中获得department_name
table department = id, department_name, total_employee
table employee = id, employee_name, id_department, email, telephone, gender, status我试过model.Employee
public function department()
{
return $this->belongsTo(Department::class);
}controllers.EmployeeControllers
public function index()
{
$data_employee = Employee::with('department')->get();
return view ('employee.index', compact('data_employee '));
}有视野
@forelse ($data_employee as $item)
<tr>
<td class="text-center">{{ $item->employee_name}}</td>
<td class="text-center">{{ $item->department->department_name}}</td>
<td class="text-center">{{ $item->email}}</td>
<td class="text-center">{{ $item->telephone}}</td>
</tr>
@endforelse但上面写着
尝试在null上读取属性"department_name“
我做错什么了。
发布于 2022-09-28 11:55:00
请更换model.Employee
public function department()
{
return $this->belongsTo(Department::class, 'id_department');
}发布于 2022-09-28 11:55:25
首先,你需要把你的关系写好。
public function department()
{
// You have to provide correct model name here.
return $this->belongsTo(Department::class);
}其次,雄辩者通过检查关系方法的名称并用_id__后缀来确定外键名。因此,在您的示例中,雄辩者假设Employee模型有一个department_id列。但是,电话模型上的外键不是department_id,您可以将自定义密钥名作为第二个参数传递给belongsTo方法。
public function department()
{
return $this->belongsTo(Department::class, 'id_department');
}https://stackoverflow.com/questions/73880755
复制相似问题