I have solved the problem myself, I will write the detailed answer here in case if someone ran into same problem in future. I have also answered the question i asked on stackoverflow https://stackoverflow.com/questions/63989814/laravel-pivot-model-relationship-with-another-table
I have modified the database but the concept of problem remains the same.
https://i.stack.imgur.com/Y4ie8.png
Explination:
- items has many tiers
- tiers has one type
- tiers has many options and options has many tiers (bringing the option_tier table in scene)
- option_tier has many sizes and sizes has many option_tier (bringing the option_tier_price table in scene, with an additional field of 'price')
Solutions:
I am using [AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait][2] for eager loading pivot relations.
The concept is taken from this article [https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a][3]
The only difference is i have changed the relationship from belongTo to hasMany and it works like a charm.
Tier Model:
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Tier extends Model
{
use EagerLoadPivotTrait;
protected $table = 'tiers';
public function options()
{
return $this->belongsToMany(Option::class, 'option_tier')
->using(OptionTier::class)
->withPivot('id');
}
}
Option Model:
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Option extends Model
{
use EagerLoadPivotTrait;
protected $table = 'options';
public function tiers()
{
return $this->belongsToMany(Tier::class, 'option_tier');
}
}
OptionTier Model:
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
use Illuminate\Database\Eloquent\Relations\Pivot;
class OptionTier extends Pivot
{
use EagerLoadPivotTrait;
protected $table = 'option_tier';
public function price()
{
return $this->hasMany(OptionTierPrice::class, 'option_tier_id');
}
}
OptionTierPrice Model:
use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class OptionTierPrice extends Model
{
use EagerLoadPivotTrait;
protected $table = 'option_tier_price';
public function size()
{
return $this->belongsTo(Size::class);
}
}
Controller:
$tiers = Product::with(['tiers' => function($query) {
$query->with(['type'])
->with(['sizes'])
->with(['options.pivot.price.size'])
->with(['addons.pivot.price.size']);
}])
->get();
return $tiers;