Laravel 与复合外键的关系

Laravel relations with composite foreign keys

这是我想要实现的目标,我们有员工,每个员工都可以有一个部门的 职位,以及一个 职位 一个部门和多个 额外费用 多个部门,每个部门一个 额外费用 。我想将所有职责存储在 staff_responsibilities table

我有一个 staff table 包含以下列

然后我有 staff_responsibilities table 以下列:

职责类型可以是 PositionAdditional Charge,并且一名员工可以指定多个 Additional Charge 职责。

然后我有一个 responsibility_types table 包含以下列:


// I have no way to tell this relationship to look for a responsibility type 2 (2 is the id of the responsibility called `Designation`) 

public function designation()
    {
        return $this->hasOne(StaffResponsibility::class);
    }

// I have no way to tell this relationship to look for a responsibility type 2 
    public function position()
    {
        return $this->hasOne(StaffResponsibility::class);
    }

// Gives error: Syntax error or access violation: 1066 Not unique table/alias: 'staff_responsibilities' 
    public function additionalCharges()
    {
        return $this->belongsToMany(StaffResponsibility::class, 'staff_responsibilities','designation_id');
    }

非常感谢任何帮助。

staff_responsibilities table

responsibility_types table

称号table

Here's what I want to achieve, we have Staff and every staff can have one Position for a department, as well as one Designation for a department and multiple Additional Charges for multiple departments, one department per Additional Charge.

在我看来,为 位置指定 附加费用创建一个模型会很有帮助。感觉你可能需要normalize your database or to change staff_responsibilities as a pivot table.

但不知道您的应用程序就很难说。

要回答您的问题,您可以在 StaffResponsibility

中添加一些范围
class StaffResponsibility extends Model{

    public function scopeDesignation($query)
    {
        return $query->where('responsibility_type_id','=',2);
    }

}

并使用它

public function designation()
{
    return $this->hasOne(StaffResponsibility::class)->designation();
}

根据你写的,最后一个是 hasMany 关系而不是 manyToMany:

public function additionalCharges()
{
    return $this->belongsTo(StaffResponsibility::class, 'staff_responsibilities','designation_id')->additionalCharges();
}