John Davidson

php - Doctrine ORM: how can I fetch distinct Embedded?

0 comments
Message:


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 MyEntities 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 JOINs.


But how can I fetch all DISTINCT MyEmbeddables 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 1518 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us