【问题标题】:Call to undefined relationship [department] on model [App\\Models\\User] in Laravel API在 Laravel API 中调用模型 [App\\Models\\User] 上的未定义关系 [部门]
【发布时间】:2021-04-09 14:12:38
【问题描述】:

在我的 Laravel-8 应用程序中,我正在构建用户 API:

在用户模型中,我有这样的关系:

public function company()
{
    return $this->belongsTo('App\Models\Organization\OrgCompany');
}

public function employee(){
    return $this->hasOne(HrEmployee::class, 'user_id');
}

在员工关系中,我有:

public function gradelevel()
{
    return $this->belongsTo('App\Models\Hr\HrGradeLevel','grade_level_id','id');
} 

public function department()
{
    return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
} 

那么我的 Controller 是这样的:

public function userAll()
{
    try{
        if(!Auth::user()->hasPermissionTo('user_access'))
        {
            return response()->json([ "message" => 'You are not authorised to view Users'], 401);
        }
        return response()->json(User::with('employee','company','department','gradelevel')->get(), 200);
    } catch (\Exception $e) {
        Log::error($e);
        $message = $e->getMessage();
        return response()->json(['error' => 1, 'message' => $message]);
        }
}

当我尝试在 POSTMAN 中测试它时,我得到了这个错误:

“消息”:“调用模型 [App\Models\User] 上的未定义关系 [部门]。”

如何访问不直接链接到用户而是链接到员工的部门和年级关系?

谢谢

【问题讨论】:

  • 你需要在 User 模型上定义 department 关系,你在 Employee 模型上定义了它
  • 如果用户模型与员工模型有关系,那么你可以这样做:User::with('employee','company','employee.department','emloyee.gradelevel')

标签: laravel api


【解决方案1】:

正确的语法是:

User::with(['company', 'employee.department', 'employee.gradelevel'])->get();

嵌套关系加载使用. 表示法(relationship、other.nested 等)。如果加载嵌套关系,它也会加载父关系,因此您不必这样做['company', 'employee', 'employee.department', 'employee.gradelevel']

详情请参阅https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

【讨论】:

    【解决方案2】:

    您想使用with() 包含嵌套关系。您应该使用点注释来声明关系的路径。

    with('employee.department', 'employee.gradelevel', 'company')
    

    【讨论】:

      猜你喜欢
      • 2019-12-01
      • 2022-12-09
      • 2022-01-26
      • 2021-03-09
      • 2021-06-21
      • 2023-02-06
      • 2020-06-20
      • 2020-01-28
      • 2021-03-19
      相关资源
      最近更新 更多