Let's say that we are in the following situation:
/**
* This is a Doctrine Embeddable
*/
class MyEmbeddable {
private $_field1;
private $_field2;
}
/**
* This is a Doctrine Entity and is mapped to a table
*/
class MyEntity {
private int $_id;
private string $_name;
// Different `MyEntities` can have a `MyEmbeddable` containing exactly the same data
private MyEmbeddable $_embedded;
}
Let's suppose that the DB table is the following:
+----+----------------+-----------------+-----------------+
| id | name | embedded_field1 | embedded_field2 |
+----+----------------+-----------------+-----------------+
| 1 | an_entity_name | some_value | 42 |
+----+----------------+-----------------+-----------------+
I know that I can fetch all MyEntitie
s with the following code:
$qb = $entityManager->createQueryBuilder();
$q = $qb->select('e')
->from(MyEntity::class, 'e')
->where(...)
->getQuery();
print_r($q->getResult()); // An `array` of `MyEntitie`s
And I know how to use ->distinct()
to filter potential duplicate values arising from JOIN
s.
But how can I fetch all DISTINCT
MyEmbeddable
s of MyEntity
-es? What I have tried:
$qb = $entityManager->createQueryBuilder();
$q = $qb->select('e._embedded')
->distinct()
->from(MyEntity::class, 'e')
->where(...)
->getQuery();
print_r($q->getResult());
// error `MyEntity has no field or association named _embedded`
My Answer:
> createQueryBuilder();
$qb->select('e')
->from('MyEntity', 'e');
$entities = $qb->getQuery()->getResult();
But if you want to fetch distinct `MyEmbeddable` values, you can use the `DISTINCT` keyword in your query like this:
php
$qb = $entityManager->createQueryBuilder();
$qb->select('DISTINCT e.embedded')
->from('MyEntity', 'e');
$embeddables = $qb->getQuery()->getResult();
This will fetch only distinct `MyEmbeddable` values from your `MyEntity` entities.
Rate this post
3 of 5 based on 6738 votesComments