php - Laravel - 使用 Eloquent 在数据透视表上多对多
问题描述
我有三个要关联的表。Shipment_methods、Ship_companies和Payment_methods。
关系:
Shipment_methods <- pivot1 -> Ship_companies
pivot1 <- pivot2 -> Payment_methods
好吧,我想做的是将例如 ShipmentMethod_A 附加到 ShipCompany_B 并且对于此记录(来自 pivot1),我想通过 pivot2 表从 Payment_method 表附加记录。
发货方式型号:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->withPivot('price_kc', 'price_ha');
}
船公司型号:
public function shipment_methods()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'ship_company_id', 'shipment_method_id');
}
我需要做的是我想检索特定 ShipmentMethod 的 ShipCompany 的所有付款,例如
ShipmentMethods->ship_companies->pivot->payments_methods
谢谢。
解决方案
我认为最好的方法是为您设置一个Model
可以扩展的Pivoted
类pivot1。pivot1应该有要在pivot2中使用的id列。所以代码应该是这样的,
发货方式型号:
public function ship_companies()
{
return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->using('App\pivot1')->withPivot('id','price_kc', 'price_ha');
}
请注意,我已将 id 放入withPrivot
和 chainusing()
方法
你的pivot1模型应该是这样的,
枢轴1型号:
use Illuminate\Database\Eloquent\Relations\Pivot;
class pivot1 extends Pivot
{
public function Payment_methods()
{
return $this->belongsToMany(Payment_methods::class, 'pivot2_table_name', 'pivot1_id', 'payment_method_id');
}
}
最后你可以这样做以保存到pivot2
ShipmentMethods->ship_companies->pivot->payments_methods()->sync([payment_method_ids])
由于所有枢轴关系都返回一个数组集合,请注意您需要循环ShipmentMethods->ship_companies
关系才能获得枢轴关系。
希望这可以帮助!