【问题标题】:Laravel hasOneThrough Relationship In ModelLaravel hasOneThrough 模型中的关系
【发布时间】:2021-10-27 09:33:55
【问题描述】:

假设我有一个如下的数据库架构:

Department -> id | department_name
Employee -> id | department_id | name
Attendance -> id | employee_id | timestamp

我可以使用hasManyThrough 关系从Department 模型中检索部门的所有出勤率,如下所示:

public function attendance() {
    return $this->hasManyThrough(EmployeeAttendance::class, Employee::class, 'department_id', 'employee_id', 'id', 'id');
}

但是,我试图做相反的事情,即从考勤模型中检索员工的部门。我曾尝试使用hasOneThrough 关系,但我无法得到它。我已经查看了文档以及其他相同的教程。任何关于如何通过Attendance 模型中的关系来帮助我的帮助将不胜感激。

【问题讨论】:

    标签: laravel eloquent has-one-through


    【解决方案1】:

    您可以预先加载嵌套关系,您可以在documentation 中查看有关它们的更多信息。

    Attendance::with('employee.department')->find($id);
    

    如果您尝试在出勤率和部门之间建立关系,您可能需要执行以下操作: 在考勤模型中:

    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }
    

    在员工模型中:

    public function department()
    {
        return $this->belongsTo(Department::class);
    }
    

    【讨论】:

    • 你为什么在你的答案中使用多对多关系?
    猜你喜欢
    • 2020-10-24
    • 2023-02-04
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多