I built a loop in PHP that makes 500 SQL queries but I would like to merge the 500 SQL queries into one and get the same return (the companies and the count of the users on each company)
Example of PHP code
$companies = array();
foreach ($fortune500Service->listAll() as $c ){
$count = $entityManager
->createQueryBuilder()
->select("count(u)")
->from("AppBundle\Entity\User","u")
->where("u.email LIKE :d")
->setParameter("d", "%@" . $c["Domain"])
->getQuery()->getSingleScalarResult();
if ($count == 0) {
continue;
}
$companies[] = array(
"Domain" => $c["Domain"],
"Company" => "{$c["Company"]} ({$count})",
);
}
return $companies;
Example of 2 SQL queries that I want to merge
Query 1
SELECT
count(u0_.id)
FROM
user u0_
WHERE
u0_.email LIKE '%@company1.com'
Query 2
SELECT
count(u0_.id)
FROM
user u0_
WHERE
u0_.email LIKE '%@company2.com'
I prefer a solution using createQueryBuilder http://symfony.com/doc/current/book/doctrine.html#querying-for-objects-using-doctrine-s-query-builder but I am happy also with an SQL native query.
u0_.email LIKE '%@somecompany.com'conditions into an array and join them withOR.u0_.email LIKE '%@somecompany.com'conditions into an array and join them withOR. The result that I will get is the number of users in any company. For example 4 users in total. I want this result: 2 Users Company1 and 2 Users Company2.UNIONthem.