framework: [5.4] whereHas on polymorphic relations not work

  • Laravel Version: 5.4
  • PHP Version: 7.1
  • Database Driver & Version: PostgreSQL 9

Description:

when try whereHas method on a polymorphic relation does not works as expected.

Statistics::whereHas('applicable', function ($query) {
        $query->where('employee.id', 1);
    })->toSql();
select * from "statistics" where exists (select * from "statistics" as "laravel_reserved_0" where "laravel_reserved_0"."id" = "laravel_reserved_0"."applicable_id" and "employee"."id" = ?)

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 7
  • Comments: 18 (8 by maintainers)

Most upvoted comments

i’m currently using this code in my own project

my Model (\App\Production\Models\Production Model)

public function detail()
{
    return $this->morphTo('detail');
}

public function scopeDetailable($query, $callable = null)
{
    list($type, $key) = $this->getPolymorphicFields();

    $this->newQuery()->distinct()->get([$type])->keyBy($type)->map(function ($model)  use ($type) {
        return (new $model->{$type})->getTable();
    })->each(function ($table, $modelClass) use (&$query, $key, $callable) {
        $model = new $modelClass;

        $query = $query->orWhereExists(function ($query) use ($table, $model, $key, $callable) {
            $query->select('*')->from($table)->whereRaw("{$this->getTable()}.{$key} = {$table}.{$model->getKeyName()}")
                ->when($callable instanceof \Closure, $callable);
        });
    });

    return $query;
}

protected function getPolymorphicFields()
{
    $relation = $this->detail();

    return [$relation->getMorphType(), $relation->getForeignKey()];
}

my Controller

\App\Production\Models\Production::detailable(function ($query) {
    $query->whereDate('panen_future_date', '2017-02-08');
})->with('detail')->get()

and it works for my use case.

please note that all model related to \App\Production\Models\Production model have ‘panen_future_date’ filed in its table.

i have reproduced in a fresh laravel project. here is the https://github.com/bunnypro/querying-polymorphic

just migrate and use DummySeeder class for seeding. i didn’t write any unit testing, but i wrote a route in web route (web.php) for testing, just serve and access /?search=your search