Skip to content

Commit d2de1c2

Browse files
committed
select exists for repositories trait
1 parent a7fcdc5 commit d2de1c2

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Features
1818
* Fix creating [default schema in down migrations for pgsql](https://github.com/doctrine/dbal/issues/1110)
1919
* [JSON(B) functions](https://www.postgresql.org/docs/current/functions-json.html) (in progress)
2020
* JSON(B) types based on object models (in progress, requires symfony/serializer)
21+
* [Trait](src/ORM/Trait/ExistsMethodRepositoryTrait.php) for easy use of [SELECT EXISTS(...)](https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS) in your entity repositories
2122

2223
Requirement
2324
-----------
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Pfilsx\PostgreSQLDoctrine\ORM\Trait;
6+
7+
use Doctrine\DBAL\Exception;
8+
9+
trait ExistsMethodRepositoryTrait
10+
{
11+
/**
12+
* @param array<string, mixed> $predicates
13+
*
14+
* @throws Exception
15+
*
16+
* @return bool
17+
*/
18+
public function exists(array $predicates): bool
19+
{
20+
$subQb = $this->createQueryBuilder('_sub')->select('1');
21+
22+
$parameters = [];
23+
$idx = 1;
24+
foreach ($predicates as $field => $value) {
25+
if (\is_array($value)) {
26+
$subQb->andWhere($subQb->expr()->in("_sub.$field", $value));
27+
28+
continue;
29+
}
30+
31+
if (\is_null($value)) {
32+
$subQb->andWhere($subQb->expr()->isNull("_sub.$field"));
33+
34+
continue;
35+
}
36+
37+
if (\is_object($value)) {
38+
if (!\method_exists($value, 'getId')) {
39+
throw new \RuntimeException("Unable to cast object predicate value to scalar for key: $field");
40+
}
41+
42+
$value = $value->getId();
43+
}
44+
45+
$subQb->andWhere("_sub.$field = ?$idx");
46+
$parameters[$idx] = $value;
47+
++$idx;
48+
}
49+
50+
return (bool) $this->_em
51+
->getConnection()
52+
->createQueryBuilder()
53+
->select("EXISTS({$subQb->getQuery()->getSQL()})")
54+
->setParameters($parameters)
55+
->fetchOne()
56+
;
57+
}
58+
}

0 commit comments

Comments
 (0)