繁体   English   中英

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

[英]Laravel - Many to Many on pivot table with Eloquent

我有三个要联系的桌子。 Shipment_methods,Ship_companiesPayment_methods。

关系:

装运方法<-axis1->装运公司

枢纽1 <-枢纽2->付款方式

好吧,我想做的是,例如,将ShipmentMethod_A附加到ShipCompany_B上,并且为此记录(来自pivot1),我想将支付方式表中的记录附加到pivot2表中。

发货方法模型:

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类。 ivot1应该在id2中使用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放入withPrivotusing()方法进行链接

您的pivot1模型应该是这样的,

ivot1型号:

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关系以获取数据透视关系。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM