I want to show a count of a related table to the one building the query builder. The working native query is the following one:
select id, name, (select count(*) from houses where status = 1 and street_id = s.id) as total from streets s;
In the former query I want to show the street info and also how many houses there are in each street.
I started the query builder like this
$queryBuilder = $this->createQueryBuilder('s');
$queryBuilder
->select('
s.id as street_id, s.name as name')
But I don’t know how to add this count. On another hand I tested this query natively with joins and it is very slow, so I would need to avoid them.
House and Street are both ORM Entities
2
Answers
If native Sql is slow then ORM will be not faster.
first question is why query is slow, if there is many data, try to load count of houses via ajax async, or maybe you can limit you data which you can fetch from db.
To answer how you could add the
count
to the query builder:You mentioned avoiding JOIN, you maybe able to avoid the whole query by adding a collection of house in the street entity and using
->getHouses()
, but I guess Doctrine would still be doing a SQL join under the hood.