I have an Entity called Company
. The associations are mapped like this:
manyToOne:
headCompany:
targetEntity: CompanyEntity
inversedBy: headCompany
oneToMany:
subsidiaries:
targetEntity: CompanyEntity
mappedBy: headCompany
Everything works fine. A company can be subsidiary of another and/or have its own subsidiaries.
Now, I need to filter Companies that ARE head companies of others, or companies that have subsidiaries.
I can do that directly with SQL:
SELECT c.id, COUNT(s.headCompany_id) subsidiaries FROM companies c LEFT JOIN companies s ON s.headCompany_id = c.id GROUP BY c.id HAVING subsidiaries > 0
Resulting something like this:
+----+--------------+
| id | subsidiaries |
+----+--------------+
| 1 | 3 |
+----+--------------+
| 5 | 2 |
+----+--------------+
Then, companies 1 and 5 would fit my filter because they both have subsidiaries.
How can I achieve this same result using Doctrine Query Builder?
My attempts were:
$query = $qb->select('e')
->from('CompanyEntity', 'e')
->orderBy('e.id', 'ASC')
->join('e.headCompany', 'h')
->addSelect("COUNT(h.id) as subsidiaries")
->groupBy("e.id")
->having("subsidiaries > 0");
This one returns the subsidiaries, not the head companies.
->where($qb->expr()->isNotNull("e.subsidiaries"))
And this is not allowed by Doctrine apparently.