5 months ago

belongsToMany inverted relationship

Posted 5 months ago by zefex

I have 3 classes: ad, plan and subscriptions. subscriptions is the pivot table, meaning that an ad can have multiple plans and subscriptions is the one holding both 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:


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

Please sign in or create an account to participate in this conversation.