[英]relate pivot table to another table in laravel
我与以下结构存在多对多关系:
|Table receipts |
|- id |
|- code |
|- date |
-----------------------
|Table plans |
|- id |
|- number |
|- name |
-----------------------
|Table plan_receipt |(Pivot)
|- id |
|- receipt_id |
|- plan_id |
|- employee_id |
-----------------------
|Table employees |
|- id |
|- name |
-----------------------
如您所见,我有一个典型many-to-many
关系生成一个 pivot 表,其中包含所述表的键,但我还有第三个foreign key
引用另一个表"employees"
,我如何关联这个表员工和我的桌子? pivot? 尝试为 pivot 表创建一个 model 并建立关系,除了使用->using()
但到目前为止它对我没有用,我留给你一个我当前模型的例子。
class Receipt extends Model
{
public function plans()
{
return $this->belongsToMany(Plan::class)->using(PlanReceipt::class);
}
}
class Plan extends Model
{
public function receipts()
{
return $this->belongsToMany(Receipt::class);
}
}
class PlanReceipt extends Pivot
{
protected $table = 'plan_receipt';
public function employee()
{
return $this->belongsTo(Employee::class, 'employee_id');
}
}
class Employee extends Model
{
public function plan_receipt()
{
return $this->hasMany(PlanReceipt::class, 'id');
}
}
猜想你需要进行以下两个更改
class Employee extends Model
{
public function plan_receipt()
{
//Specifying foreign key is not required as it is as per Eloquent convention
return $this->hasMany(PlanReceipt::class);
//If you want to specify the keys then it should be
// return $this->hasMany(PlanReceipt::class, 'employee_id', 'id');
}
}
class PlanReceipt extends Pivot
{
protected $table = 'plan_receipt';
//Assuming the id column on plan_receipt table is auto incrementing
public $incrementing = true;
public function employee()
{
//return $this->belongsTo(Employee::class, 'employee_id');
//Specifying foreign key is not required as it is already as per Laravel Eloquent convention
return $this->belongsTo(Employee::class);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.