拉拉维尔口才关系与 4 张桌子(3 个模型 + 1 个表)



嗨,我有这 4 张桌子

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

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

位置: 位置ID, 职位类型

employee_deployment: 员工部署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表(中。

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

class Deployment extends Model
{
public function employee()
{
return $this->hasOne('AppEmployee');
}
public function department()
{ 
return $this->hasOne('AppDepartment');
}
public function position()
{
return $this->hasOne('AppPosition');
}
}
class Employee extends Model
{
public function deployment()
{
return $this->belongsTo('AppDeployment');
}
}
class Position extends Model
{
public function deployment()
{
return $this->belongsTo('AppDeployment');
}
}
class Department extends Model
{
public function deployment()
{
return $this->belongsTo('AppDeployment');
}
}

如果您希望能够直接访问员工与职位或职位与部门或员工与部门之间的关系,您还可以将hasOneThrough关系添加到其他3个模型中

public function employee()
{
return $this->hasOneThrough('AppEmployee', 'AppDeployment');
}
public function department()
{
return $this->hasOneThrough('AppDepartment', 'AppDeployment');
}
public function position()
{
return $this->hasOneThrough('AppPosition', 'AppDeployment');
}

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

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

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

最新更新