I have the following models: Account and Campaign
These two models have a belongsToMany relationship and thus a corresponding pivot table. I also have an explicit pivot model AccountCampaign.
My Campaign model has the following:
public function accounts(): BelongsToMany
{
return $this->belongsToMany(Account::class)
->using(AccountCampaign::class)
->withPivot(['campaign_stage_id', 'sort_order'])
->withTimestamps();
}
As you can see, there is a foreign key to another model CampaignStage which has a belongsTo relationship to the pivot model. I want to eager load this model but I'm not sure how?
My pivot model has the relationship setup:
public function stage(): BelongsTo
{
return $this->belongsTo(CampaignStage::class, 'campaign_stage_id');
}
I tried the following unsuccessfully:
Campaign::accounts()->with('pivot.stage')->get()
I've also tried adding the following to my pivot model:
protected $with = ['stage'];
But that doesn't work either. Is this even possible?
I know my relationships are good because the following works:
$campaign->accounts->first()->pivot->stage->name;
Thanks.