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

[5.6] add withSum to framework #25290

Closed
wants to merge 7 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
58 changes: 58 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,64 @@ public function withCount($relations)

return $this;
}
/**
* Add subselect queries to sum the relations.
*
* @param mixed $relations
* @param string $column
* @return $this
*/
public function withSum($relations, $column)
{
if (empty($relations)) {
return $this;
}

if (is_null($this->query->columns)) {
$this->query->select([$this->query->from.'.*']);
}

$relations = is_array($relations) ? $relations : [$relations];

foreach ($this->parseWithRelations($relations) as $name => $constraints) {
// First we will determine if the name has been aliased using an "as" clause on the name
// and if it has we will extract the actual relationship name and the desired name of
// the resulting column. This allows multiple counts on the same relationship name.
$segments = explode(' ', $name);

unset($alias);

if (count($segments) == 3 && Str::lower($segments[1]) == 'as') {
list($name, $alias) = [$segments[0], $segments[2]];
}

$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->getRelationExistenceSumQuery(
$relation->getRelated()->newQuery(), $this, $column
);

$query->callScope($constraints);

$query = $query->mergeConstraintsFrom($relation->getQuery())->toBase();

if (count($query->columns) > 1) {
$query->columns = [$query->columns[0]];
}

// 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 = $alias ?? Str::snake($name.'_sum');

$this->selectSub($query, $column);
}

return $this;
}

/**
* Add the "has" condition where clause to the query.
Expand Down
17 changes: 15 additions & 2 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,15 +194,28 @@ public function getRelationExistenceCountQuery(Builder $query, Builder $parentQu
$query, $parentQuery, new Expression('count(*)')
)->setBindings([], 'select');
}

/**
* Add the constraints for a relationship sum query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param string $column
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationExistenceSumQuery(Builder $query, Builder $parentQuery, $column)
{
return $this->getRelationExistenceQuery(
$query, $parentQuery, new Expression("sum(`{$column}`)")
)->setBindings([], 'select');
}
/**
* Add the constraints for an internal relationship existence query.
*
* Essentially, these queries compare on column names like whereColumn.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
Expand Down
37 changes: 37 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,43 @@ public function testHasWithConstraintsAndHavingInSubqueryWithCount()
$this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
}

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

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

$this->assertEquals('select `eloquent_builder_test_model_parent_stubs`.*, (select sum(`foo_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','foo_id');

$this->assertEquals('select `id`, (select sum(`foo_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');
}],'foo_id');

$this->assertEquals('select `id`, (select sum(`foo_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','foo_id');

$this->assertEquals('select `eloquent_builder_test_model_parent_stubs`.*, (select sum(`foo_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` from `eloquent_builder_test_model_parent_stubs`', $builder->toSql());
}
public function testHasNestedWithConstraints()
{
$model = new EloquentBuilderTestModelParentStub;
Expand Down