首页 > 解决方案 > Laravel - 使用 Eloquent 在数据透视表上多对多

问题描述

我有三个要关联的表。Shipment_methodsShip_companiesPayment_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

谢谢。

标签: phplaraveleloquentmany-to-many

解决方案


我认为最好的方法是为您设置一个Model可以扩展的Pivotedpivot1pivot1应该有要在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关系才能获得枢轴关系。

希望这可以帮助!


推荐阅读