Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter by aggregations #49

Closed
t1gor opened this issue Jan 11, 2018 · 2 comments
Closed

Filter by aggregations #49

t1gor opened this issue Jan 11, 2018 · 2 comments

Comments

@t1gor
Copy link

t1gor commented Jan 11, 2018

Hi.

Somhow I couldn't find any info on the topic of filtering by aggregates, so here's my quesion. I have two models: Group -{has many}-> Student. I would like to filter all groups with average student age more then Y (age is a calculated field, e.g. AVG(TIMESTAMPDIFF(YEAR, person.dob, NOW())) AS age)

I am pretty new to Laravel in general, so sorry if this is not a question about filters exactly.

Thanks in advance for your help.

@Tucker-Eric
Copy link
Owner

You can do it a couple different ways.

Using whereRaw():

If you are doing this in the GroupFilter:

public function averageAge($age)
{
    return $this->related('students', function($query) use ($age) {
        return $query->whereRaw('AVG(TIMESTAMPDIFF(YEAR, person.dob, NOW())) < ?', [$age]);
    });
}

Outside of a filter on the model itself:

Group::whereHas('students', function($query) use ($age) {
    return $query->whereRaw('AVG(TIMESTAMPDIFF(YEAR, person.dob, NOW())) < ?', [$age]);
})->get();

Or you can do it with a selectSub() and has():

In the GroupFilter:

public function averageAge($age)
{
    return $this->related('students', function($query) use ($age) {
        return $query->selectSub('AVG(TIMESTAMPDIFF(YEAR, person.dob, NOW()))', 'age')
            ->having('age', '>', $age);
    });
}

Or on the model itself:

Group::whereHas('students', function($query) use ($age) {
    return $query->selectSub('AVG(TIMESTAMPDIFF(YEAR, person.dob, NOW()))', 'age')
        ->having('age', '>', $age);
})->get();

@t1gor
Copy link
Author

t1gor commented Jan 18, 2018

Thanks a lot for those examples!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants