簡體   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