【问题标题】:Laravel hasManyThrough with multiple key fieldsLaravel hasManyThrough 有多个关键字段
【发布时间】:2016-03-07 20:18:19
【问题描述】:

我正在尝试与多个关键字段建立我认为的 Laravel hasManyThrough 关系。我的数据库如下所示:

  • 员工

    • 身份证
    • team_id > 参考团队
    • 姓名
  • 团队

    • 身份证
    • teamleader1_user_id > 参考员工
    • teamleader2_user_id > 参考员工
    • teamleader3_user_id > 参考员工

我知道数据库设置不太理想,但由于它是一个外部应用程序数据库,我无法更改任何内容。

在我的 Employee 模型中,我想创建一个关系,以便可以通过 Teams 中的一个 teamleader 字段提取属于某个员工的所有员工。我该如何设置?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    你可以把它当作ManyToMany关系来处理,捆绑了三个OneToMany。

    class Team extends Model{
    public function employees()
    {
        return $this->hasMany('App\Employee');
    }
    
    public function teamleader1()
    {
        return $this->hasOne('App\Employee','teamleader1_user_id');
    }
    
    public function teamleader2()
    {
        return $this->hasOne('App\Employee','teamleader2_user_id');
    }
    
    public function teamleader3()
    {
        return $this->hasOne('App\Employee','teamleader3_user_id');
    }
    }
    
    class Employee extends Model {
        public function teams()
        {
            return $this->belongsToMany('App\Team');
        }
    }
    

    您可能有一个名为employee_team 的中间表,其中包含该“名称”属性。有关更多信息,您可以查看 Laravel 文档上的 Many to many 关系。

    【讨论】:

    • 好的,但是我如何通过所有团队领导关系一次获取属于另一个员工的所有员工,例如 Employee->employees()?
    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2018-07-24
    • 2018-10-18
    • 2023-03-09
    • 1970-01-01
    • 2015-07-27
    • 2020-10-14
    • 1970-01-01
    相关资源
    最近更新 更多