【问题标题】:Laravel Eloquent Relationship with 4 tables (3 model + 1 table)Laravel Eloquent 关系与 4 个表(3 个模型 + 1 个表)
【发布时间】:2019-12-04 20:59:19
【问题描述】:

嗨,我有这 4 张桌子

员工: 员工ID, 员工姓名, 员工电子邮件, 员工密码

部门: 部门编号, 部门名称

职位: 位置标识, 位置类型

employee_deployment: 员工部署ID, 员工ID, 部门编号, 职位ID

我为数据透视表 employee_deployment 创建了迁移

public function up()
{
    // Set schema to create field of table
    Schema::create('employee_deployment', function (Blueprint $table) {
        $table->bigIncrements('EmployeeDeploymentID');
        $table->bigInteger('EmployeeID')->unsigned();
        $table->bigInteger('DepartmentID')->unsigned();
        $table->bigInteger('PositionID')->unsigned();

    });

    Schema::table('employee_deployment', function ($table) {
        $table->foreign('EmployeeID')->references('EmployeeID')->on('tbl_employees')->onDelete('cascade');
        $table->foreign('DepartmentID')->references('DepartmentID')->on('tbl_departments')->onDelete('cascade');
        $table->foreign('PositionID')->references('PositionID')->on('positions')->onDelete('cascade');

    });
}

有人可以帮我为每个模型建立关系吗?并将数据保存到数据透视表(employee_deployment 表)中。

【问题讨论】:

  • 这种关系在没有自定义逻辑的 Laravel 中是不可用的;一旦超过 2 个相关的表/模型,它就不再是标准的 many-to-many,并且该表作为“数据透视”表并不是真正有效的。 Stackoverflow 的概念有点宽泛,需要您进行一些研究/尝试才能找到明确的问题/解决方案。

标签: laravel eloquent-relationship


【解决方案1】:

不能以这种方式使用数据透视表同时定义 2 个关系,相反,我建议使用与其他三个模型具有一对一关系的部署模型。

class Deployment extends Model
{
  public function employee()
  {
    return $this->hasOne('App\Employee');
  }

  public function department()
  { 
     return $this->hasOne('App\Department');
  }

  public function position()
  {
    return $this->hasOne('App\Position');
  }
}
class Employee extends Model
{
  public function deployment()
  {
    return $this->belongsTo('App\Deployment');
  }
}
class Position extends Model
{
  public function deployment()
  {
    return $this->belongsTo('App\Deployment');
  }
}
class Department extends Model
{
  public function deployment()
  {
    return $this->belongsTo('App\Deployment');
  }
}

如果您希望能够直接访问 Employee 与 Position 或 Position 与 Department 或 Employee 与 Department 之间的关系,您还可以将 hasOneThrough 关系添加到其他 3 个模型中

public function employee()
{
  return $this->hasOneThrough('App\Employee', 'App\Deployment');
}

public function department()
{
  return $this->hasOneThrough('App\Department', 'App\Deployment');
}

public function position()
{
  return $this->hasOneThrough('App\Position', 'App\Deployment');
}

我认为这应该可以为您提供您正在寻找的关系 如果这些关系中的任何一个不是 1 对 1,那么您将需要 Deployment 和其他 3 个模型之间的数据透视表,但您应该能够将 hasOneThrough 切换到 hasManyThrough 以保持直接关系

对于您的迁移,如果您不在员工、部门和职位模型上使用常规 id 列,则必须向关系中添加自定义外键定义。例如,Deployment->Employee 将是

public function employee()
{
  return $this->hasOne('App\Employee', 'EmployeeID', 'EmployeeID');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2016-02-06
    • 2014-01-03
    • 2016-05-02
    • 2013-04-20
    相关资源
    最近更新 更多