Skip to content

Commit

Permalink
relationships: fixed counting entities when multiplied by joins [closes
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Apr 10, 2020
1 parent 3ff59e1 commit 8ac61d4
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Mapper/Dbal/RelationshipMapperManyHasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private function fetchCounts(QueryBuilder $builder, array $values)
$result = $this->processMultiCountResult($builder, $values);

} else {
$builder->addSelect('COUNT(%column) as count', "$targetTable.$this->primaryKeyTo");
$builder->addSelect('COUNT(DISTINCT %column) AS [count]', "$targetTable.$this->primaryKeyTo");
$builder->orderBy(null);
$builder->andWhere('%column IN %any', "$targetTable.$this->primaryKeyFrom", $values);
$builder->groupBy('%column', "$targetTable.$this->primaryKeyFrom");
Expand Down
2 changes: 1 addition & 1 deletion src/Mapper/Dbal/RelationshipMapperOneHasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ private function fetchCounts(QueryBuilder $builder, array $values)

} else {
$builder->orderBy(null);
$builder->addSelect('COUNT(%column) AS [count]', "{$sourceTable}.{$targetStoragePrimaryKey}");
$builder->addSelect('COUNT(DISTINCT %column) AS [count]', "{$sourceTable}.{$targetStoragePrimaryKey}");
$builder->andWhere('%column IN %any', "{$sourceTable}.{$this->joinStorageKey}", $values);
$builder->groupBy('%column', "{$sourceTable}.{$this->joinStorageKey}");
$result = $this->connection->queryArgs($builder->getQuerySql(), $builder->getQueryParameters());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,21 @@ class RelationshipManyHasManyTest extends DataTestCase

Assert::same(1, \count($tag->books));
}


public function testCountStoredOnManyHasManyRelationshipCondition()
{
$tag = $this->orm->tags->getById(1);
$books = $tag->books->get()->findBy([
'this->author->id' => 1,
]);
Assert::same(1, $books->countStored());

$books = $tag->books->get()->findBy([
'this->author->tagFollowers->author->id' => 1,
]);
Assert::same(1, $books->countStored());
}
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,23 @@ class RelationshipOneHasManyTest extends DataTestCase

Assert::same(1, \count($author->books));
}


public function testCountStoredOnOneHasManyRelationshipCondition()
{
$publisher = $this->orm->publishers->getById(1);
$books = $publisher->books->get()->findBy([
'this->tags->id' => 1,
]);
Assert::same(1, $books->countStored());

$books = $publisher->books->get()->findBy([
ICollection::OR,
'this->title' => 'Book 1',
'this->tags->id' => 1,
]);
Assert::same(1, $books->countStored());
}
}


Expand Down

0 comments on commit 8ac61d4

Please sign in to comment.