laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.39k stars 10.98k forks source link

[5.2] WhereHas on polymorphic relation #13585

Closed azorgh closed 8 years ago

azorgh commented 8 years ago

Hi guys.

I'm trying to make a Eloquent request with polymorphic relations and conditions. So, I have models :

In my example, I must get only MainClass where 'column' in my polymorphic relation was null. So, i wrote this :

$results = MainClass::whereHas('detail', function($query){
                $query->whereNotNull('column');
            })->get();

But a QueryException was thrown:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'column' in 'where clause' (SQL: 
    select * from `main_class` where exists (
        select * from `main_class` as `laravel_reserved_0` where `laravel_reserved_0`.`id` = `laravel_reserved_0`.`type_id` and `parent_id` is not null
    )
)

Except this conditions, all polymorphic relations works perfectly.

I'm sorry if it's not a bug, but all my app works well without this condition ! Thanks (and good luck :) )

PS: I'm using Laravel 5.2.32.

milewski commented 8 years ago

i have the some problem.....

ericmagnuson commented 8 years ago

+1

From what I've read, whereHas doesn't support polymorphic relations. Did anyone else come to that conclusion?

milewski commented 8 years ago

well at the time i was looking for this whereHas stuff... and it wasnt working the way i expected... i come out with a different approach which works great for my case.. have a look.

public function scopeActive(Builder $query)
    {
        foreach ($stages = ['idea', 'synapse', 'script'] as $stage) {

            $query->orWhereHas(array_shift($stages), function (Builder $query) {
                $query->where('active', true)->orHas('submission');
            });

            foreach ($stages as $model) {
                $query->whereDoesntHave($model);
            }

        }

        $query->where('active', true);
    }

my polymorphism relation is like this Project -> ['idea', 'synapse', 'script'] -> its like levels... 1 2 3 u cant have the 3 before having the 2 ..

ericmagnuson commented 8 years ago

Thanks for sharing this. Something like this might fit my needs, too.

jolora commented 8 years ago

+1 ...I would love to be able to use whereHas on polymorphic relations

ayaka209 commented 8 years ago

+1 here.

GrahamCampbell commented 8 years ago

Closing since this is a feature request, not a bug report. If you have an implementation idea, please open an issue on internals.

sergey-rud commented 7 years ago

Hi!

I use Laravel 5.2.45, seems it haven't fixed yet. Perhaps in future will be good to throw Exception or write a note in the documentation about such behaviour.

Best regards.

nacr commented 7 years ago

+1 for this please!

MikeMnD commented 7 years ago

+1

DakIyq commented 7 years ago

+1

allanzi commented 7 years ago

+1

skcin7 commented 6 years ago

Hi +1