Laravel - 使用 Eloquent 在数据透视表上进行多对多

Mic*_*túz 5 php many-to-many laravel eloquent

我有三个想要关联的表。Shipment_methodsShip_companiesPayment_methods

关系:

Shipment_methods <- hub1 -> Ship_companies

数据透视表1 <- 数据透视表2 -> Payment_methods

好吧,我想做的是,例如 ShipmentMethod_A 附加到 ShipCompany_B,对于此记录(来自数据透视表 1),我想通过数据透视表 2 表附加来自 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');
}
Run Code Online (Sandbox Code Playgroud)

船公司型号:

public function shipment_methods()
{
    return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'ship_company_id', 'shipment_method_id');
}
Run Code Online (Sandbox Code Playgroud)

我需要做的是我想检索特定 ShipmentMethod 的 ShipCompany 的所有付款,例如

ShipmentMethods->ship_companies->pivot->payments_methods
Run Code Online (Sandbox Code Playgroud)

谢谢。

Cha*_*ara 5

我认为最好的方法是为您提供一个Model扩展Pivotedhub1。ivot1应该有id列以在ivot2中使用。所以代码应该是这样的

发货方式型号:

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');
}
Run Code Online (Sandbox Code Playgroud)

请注意,我已将 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

最后你可以这样做来保存到pivot2

ShipmentMethods->ship_companies->pivot->payments_methods()->sync([payment_method_ids])
Run Code Online (Sandbox Code Playgroud)

由于所有枢轴关系都返回数组集合,请注意,您需要循环ShipmentMethods->ship_companies关系才能获得枢轴关系。

希望这可以帮助!