#Is it possible to eager load a relationship on a pivot model?

2 messages · Page 1 of 1 (latest)

worn hinge
#

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.

glacial crater
#

I've never tried that scenario but I know that pivot classes have some limitations (like local scopes on the pivot not working as you might expect) and they're only really meant to connect 2 entities, not 3. So to me it sounds like you'd be better off by making AccountCampaign a normal model.