Laravel relationship Column 'id' in where clause is ambiguous

user3844579 picture user3844579 · Mar 2, 2017 · Viewed 9.3k times · Source

I have courses and subscription types. I want to get all the courses that has a given subscription type. My attempt:

$courses=Course::wherehas('subscriptionType',function ($q)
        {
            return $q->where('id','1');
        })->get();

But this fails:

Column 'id' in where clause is ambiguous

Any tips on doing this?

Answer

Muhammad Inaam Munir picture Muhammad Inaam Munir · Mar 3, 2017

I tested you code and it was working fine without any changes. May be something is wrong with your relationship definitions.

However you can make it run by making following changes.

replace return $q->where('id','1'); with return $q->where('subscriptiontypes.id','1'); I assumed that table name for subscriptiontype model is subscriptiontypes.

full code is shown below:

$courses=Course::wherehas('subscriptiontype',function ($q)
        {
            return $q->where('subscriptiontypes.id','1');
        })->get();