belongsToMany inverted relationship

avatar
120    7 months ago

I have 3 classes: adplan and subscriptionssubscriptions is the pivot table, meaning that an ad can have multiple plans and subscriptions is the one holding both id.

subscriptions

ad_id
plan_id

In the Plan model I have this:

    public function ads() {
        return $this->belongsToMany(Ad::class, Subscription::class);
    }

This way I can get all ads that has this plan.

I wanted to do the opposite relationship, something like:

Ad::first()->plans

I tried to use hasManyThrough(Plan::class, Subscription::class) but I'm getting this error:

Undefined column: 7 ERROR: column plans.subscription_id does not exist

I don't know if hasManyThrough is the one I'm supposed to be using.

The question is: how can I make something like Ad::first()->plans?

Thank you

Answers { 1 }
avatar
7 months ago

The opposite of belongsToMany is belongsToMany:

// Ad.php

public function plans() {
    return $this->belongsToMany(Plan::class, Subscription::class);
}

Now Ad::first()->plans