staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Is it possible to use this package with the following relationships? #243

Closed ryanmortier closed 2 months ago

ryanmortier commented 2 months ago

I read through the docs but I'm having a difficult time understanding if this is possible.

I have the following models:

Account Campaign CampaignStatus

Account >---< Campaign (belongsToMany) Campaign ---< CampaignStatus (hasMany)

This is my table structure (simplified for this question):

Schema::create('accounts', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});
Schema::create('campaigns', function (Blueprint $table) {
    $table->id();
    $table->string('name');
});
Schema::create('campaign_statuses', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->foreignIdFor(Campaign::class);
});
Schema::create('account_campaign', function (Blueprint $table) {
    $table->id();
    $table->foreignIdFor(Account::class);
    $table->foreignIdFor(Campaign::class);
    $table->foreignIdFor(CampaignStatus::class);
});

When assigning an account to a campaign, they are also assigned to a campaign status via the pivot model.

I want to define a relationship to get all accounts that are associated with a given campaign status so I can do something like $campaignStatus->accounts.

ryanmortier commented 2 months ago

Wait a second... this is just another belongsToMany relationship. Duh. CampaignStatus >---< Account.

It never occured to me that the pivot is just a belongsToMany from Account to both Campaign and CampaignStatus.