Skip to content

[5.4] If there is a withCount, Than also is withSum/withAvg/withMin/withMax #18303

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

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 78 additions & 4 deletions src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,12 +154,79 @@ public function whereDoesntHave($relation, Closure $callback = null)
* @return $this
*/
public function withCount($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();

return $this->withAggregate($relations);
}

/**
* Add subselect queries to sum the relations.
*
* @param mixed $relations
* @return $this
*/
public function withSum($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();

return $this->withAggregate($relations, 'SUM');
}

/**
* Add subselect queries to max the relations.
*
* @param mixed $relations
* @return $this
*/
public function withMax($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();

return $this->withAggregate($relations, 'MAX');
}

/**
* Add subselect queries to min the relations.
*
* @param mixed $relations
* @return $this
*/
public function withMin($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();

return $this->withAggregate($relations, 'MIN');
}

/**
* Add subselect queries to min the relations.
*
* @param mixed $relations
* @return $this
*/
public function withAvg($relations)
{
$relations = is_array($relations) ? $relations : func_get_args();

return $this->withAggregate($relations, 'AVG');
}

/**
* use the MySQL aggregate functions including AVG COUNT, SUM, MAX and MIN.
*
* @param array $relations
* @param string $function
* @return $this
*/
public function withAggregate($relations, $function = 'COUNT')
{
if (is_null($this->query->columns)) {
$this->query->select([$this->query->from.'.*']);
}

$relations = is_array($relations) ? $relations : func_get_args();
// set to lower
$function = Str::lower($function);

foreach ($this->parseWithRelations($relations) as $name => $constraints) {
// First we will determine if the name has been aliased using an "as" clause on the name
Expand All @@ -173,13 +240,20 @@ public function withCount($relations)
list($name, $alias) = [$segments[0], $segments[2]];
}

// set the default column as * or primary key
$column = ($function == 'count') ? '*' : $this->model->getKeyName();

if (strpos($name, '|') !== false) {
list($name, $column) = explode('|', $name);
}

$relation = $this->getRelationWithoutConstraints($name);

// Here we will get the relationship count query and prepare to add it to the main query
// as a sub-select. First, we'll get the "has" query and use that to get the relation
// count query. We will normalize the relation name then append _count as the name.
$query = $relation->getRelationExistenceCountQuery(
$relation->getRelated()->newQuery(), $this
$query = $relation->getRelationExistenceAggregateQuery(
$relation->getRelated()->newQuery(), $this, $function, $column
);

$query->callScope($constraints);
Expand All @@ -189,7 +263,7 @@ public function withCount($relations)
// Finally we will add the proper result column alias to the query and run the subselect
// statement against the query builder. Then we will return the builder instance back
// to the developer for further constraint chaining that needs to take place on it.
$column = snake_case(isset($alias) ? $alias : $name).'_count';
$column = snake_case(isset($alias) ? $alias : $name).'_'.$function;

$this->selectSub($query->toBase(), $column);
}
Expand Down
16 changes: 16 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,22 @@ public function getRelationExistenceCountQuery(Builder $query, Builder $parentQu
);
}

/**
* Add the constraints for a relationship aggregate query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param string $type
* @param string $column
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationExistenceAggregateQuery(Builder $query, Builder $parentQuery, $type, $column)
{
return $this->getRelationExistenceQuery(
$query, $parentQuery, new Expression("$type($column)")
Copy link
Contributor

@fernandobandeira fernandobandeira Mar 13, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually should wrap the column name here:

Expression($type.'('.$this->query->getGrammar()->wrap($column).')')

The rest seems fine now 👍

);
}

/**
* Add the constraints for an internal relationship existence query.
*
Expand Down
192 changes: 192 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -669,6 +669,198 @@ public function testWithCountMultipleAndPartialRename()
$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_count", (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithSum()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withSum('foo');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_sum" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithSumAndSelect()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withSum('foo');

$this->assertEquals('select "id", (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_sum" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithSumAndMergedWheres()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withSum(['activeFoo' => function ($q) {
$q->where('bam', '>', 'qux');
}]);

$this->assertEquals('select "id", (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_sum" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertEquals(['qux', true], $builder->getBindings());
}

public function testWithSumAndRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withSum('foo as foo_bar');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_sum" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithSumMultipleAndPartialRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withSum(['foo as foo_bar', 'foo']);

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_sum", (select sum(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_sum" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMax()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMax('foo');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_max" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMaxAndSelect()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withMax('foo');

$this->assertEquals('select "id", (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_max" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMaxAndMergedWheres()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withMax(['activeFoo' => function ($q) {
$q->where('bam', '>', 'qux');
}]);

$this->assertEquals('select "id", (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_max" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertEquals(['qux', true], $builder->getBindings());
}

public function testWithMaxAndRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMax('foo as foo_bar');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_max" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMaxMultipleAndPartialRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMax(['foo as foo_bar', 'foo']);

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_max", (select max(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_max" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMin()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMin('foo');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_min" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMinAndSelect()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withMin('foo');

$this->assertEquals('select "id", (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_min" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMinAndMergedWheres()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withMin(['activeFoo' => function ($q) {
$q->where('bam', '>', 'qux');
}]);

$this->assertEquals('select "id", (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_min" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertEquals(['qux', true], $builder->getBindings());
}

public function testWithMinAndRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMin('foo as foo_bar');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_min" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithMinMultipleAndPartialRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withMin(['foo as foo_bar', 'foo']);

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_min", (select min(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_min" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithAvg()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withAvg('foo');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_avg" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithAvgAndSelect()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withAvg('foo');

$this->assertEquals('select "id", (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_avg" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithAvgAndMergedWheres()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->select('id')->withAvg(['activeFoo' => function ($q) {
$q->where('bam', '>', 'qux');
}]);

$this->assertEquals('select "id", (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bam" > ? and "active" = ?) as "active_foo_avg" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertEquals(['qux', true], $builder->getBindings());
}

public function testWithAvgAndRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withAvg('foo as foo_bar');

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_avg" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testWithAvgMultipleAndPartialRename()
{
$model = new EloquentBuilderTestModelParentStub;

$builder = $model->withAvg(['foo as foo_bar', 'foo']);

$this->assertEquals('select "eloquent_builder_test_model_parent_stubs".*, (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar_avg", (select avg(id) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_avg" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}

public function testHasWithContraintsAndHavingInSubquery()
{
$model = new EloquentBuilderTestModelParentStub;
Expand Down