Saturday, April 15, 2017

Laravel: how to use wherePivot in Polymorphic Many to Many

I want to query where isrecurring = 1 in my pivot table, but found no existing solution. Anyone have any experience and how to get all records that 'isrecurring' = 1 in Many to many Polymorphic pivot table

Example.
$enroll->products->where('isrecurring', 1);

but in enrollable pivot table
-> get all records that 'isrecurring' = 1

My Models (without wherePivot)

Enroll.php
------
public function products(){
return $this->morphedByMany('App\Models\Product', 'enrollable')->withPivot('isrecurring');
}

Product.php
----
public function enrolls(){
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring');
}

My Database

enrolls
-----
id


products
----
id

enrollables
----
enroll_id
enrollable_id
enrollable_type
isrecurring    (boolean)

I wish to use wherePivot, but seems not working and not able to query.

Product.php
----
public function enrolls(){
return $this->morphToMany('App\Models\Enroll', 'enrollable')->withPivot('isrecurring')->wherePivot('isrecurring', '=', 1);
}



via keatwei

Advertisement