Michael Motúz
Michael Motúz

Reputation: 177

Laravel - Many to Many on pivot table with Eloquent

I have three table which I wanna associate. Shipment_methods, Ship_companies and Payment_methods.

Relations:

Shipment_methods <- pivot1 -> Ship_companies

pivot1 <- pivot2 -> Payment_methods

Well, what I wanna do is e.g. ShipmentMethod_A is attached to ShipCompany_B and for this record (from pivot1) I wanna attach record from Payment_method table through pivot2 table.

ShipmentMethod Model:

public function ship_companies()
{
    return $this->belongsToMany(ShipCompany::class, 'shipment_methods_ship_companies', 'shipment_method_id', 'ship_company_id')->withPivot('price_kc', 'price_ha');
}

ShipCompany Model:

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

What I need to do is I wanna retrieve all Payments for ShipCompany of specific ShipmentMethod like

ShipmentMethods->ship_companies->pivot->payments_methods

Thanx.

Upvotes: 5

Views: 5896

Answers (1)

Chamara Abeysekara
Chamara Abeysekara

Reputation: 1332

I think best way is for you to have a Model that extend Pivoted class for you pivot1. the pivot1 should have id column to use in pivot2. so the code should be like this,

ShipmentMethod Model:

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');
}

note that I have put id in withPrivot and chain using() method

your pivot1 model should be like this,

pivot1 Model:

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');
    }
}

and at the end you can do like this to save to pivot2

ShipmentMethods->ship_companies->pivot->payments_methods()->sync([payment_method_ids])

as all pivot relationship return a collection of array note that you need to loop ShipmentMethods->ship_companies relationship to get to pivot relationship.

Hope this helps!

Upvotes: 5

Related Questions