How to merge two queries in Doctrine ORM - symfony

I have table "weights", where I have numbers of weights for various cameras.
I want to sum last numbers for this cameras, therefore I am using two queries.
First query selects max ids for every camera and second selects numbers of weight for these ids.
public function maxIds($cameras)
{
return $this->createQueryBuilder("c")
->select('MAX(c.id) ')
->where('c.camera IN (:value)')
->setParameter('value', $cameras)
->groupBy('c.camera')
->getQuery()
->getArrayResult();
}
public function totalWeight($ids)
{
return $this->createQueryBuilder("c")
->select('SUM(c.number)')
->where('c.id IN (:value)')
->setParameter('value', $ids)
->getQuery()
->getOneOrNullResult();
}
These two queries work fine, but I would like to combine them into one query.
I am trying with this:
public function testWeight($cameras)
{
$qr = $this->createQueryBuilder('c')
->select('MAX(c.id) ')
->where('c.camera IN (:value)')
->setParameter('value', $cameras)
->groupBy('c.camera');
$qr->andWhere($qr->expr()->in('c.id',
$this->_em->createQueryBuilder()
->select('SUM(c.number)')
->getDQL()
));
return $qr->getQuery()
->getOneOrNullResult();
}
But I cannot success.
How can I solve this problem?

This is untested however what you are trying to do is a sub query which you can achieve in Doctrine. I also made some minor improvements to your query:
$subQuery = $this->getEntityManager()->createQueryBuilder();
$subQuery
->select('MAX(c2.id)')
->from(MyEntity::class, 'c2')
->where($subQuery->expr()->in('c2.camera', ':cameras'));
$queryBuilder = $this->createQueryBuilder('c')
$queryBuilder
->select('SUM(c.number)')
->where($queryBuilder->expr()->in('c.id', $subQuery->getDQL()))
->setParameter('cameras', $cameras);
->getQuery()
->getOneOrNullResult();

Related

How to fetch a particular field from Symfony repository query result

Hello, I made a query in the repository Library and i am getting this result. From that i need to fetch the "code" of each of the users. Then i will load the resulting file in the form in order to build a "choice_type" with the codes. Is there a simple way to get these codes. Thank you.
Code for the query:
public function findUCodesByLibrairy($value)
{
return $this->createQueryBuilder('l')
->andWhere('u.librairy = :id')
->addSelect('u')
->leftJoin('l.users', 'u')
->setParameter('id', $value)
->getQuery()
->getResult();
}
You almost did as you need, try to request not all properties, but a specific one as shown in the example.
public function findUCodesByLibrairy($value)
{
return $this->createQueryBuilder('l')
->andWhere('u.librairy = :id')
->Select('u.code') // hier we are requesting a specific property
->leftJoin('l.users', 'u')
->setParameter('id', $value)
->getQuery()
->getResult();
}

Symfony Query Builder: remove results from a request from another requests

I have a first request (I used QueryBuilder but it is a simple findAll()):
public function findAllRosters(){
$qb = $this->createQueryBuilder('r')
;
return $qb->getQuery()
->getResult();
}
I want to remove from the results of this first query all results from another query:
public function findOtherRosters($user){
$qb = $this->createQueryBuilder('r')
->leftJoin('r.members', 'm')
->addSelect('m')
->where('m.user = :user')
->setParameter('user', $user)
;
return $qb->getQuery()
->getResult();
}
Is there a simple way? It seems that using a where NOT IN might be the way forward..
EDIT
I have tried to follow this exemple: https://stackoverflow.com/a/22616937/4228086 see my answer
Have a look at this stackoverflow solution
Here q2 is your second query, the sub result you want to reduce the first result with.
Hope that helps.
After much googling; I finally found the right Query:
public function findOtherRosters($user){
$q2 = $this->createQueryBuilder('r')
->leftJoin('r.members', 'm')
->addSelect('m')
->where('m.user = :user')
->setParameter('user', $user);
$qb = $this->createQueryBuilder('ro');
$qb
->where('ro not IN (:rosters)')
->setParameter('rosters', $q2->getQuery()->getResult())
;
return $qb->getQuery()
->getResult();
}
Hope it can help others with the same issue

Symfony2 & Doctrine2: Custom Entity Repository Query to Retrieve Single Result if Joined Table has No Associated Rows

I have two entities/tables, one for Counties and one for Cities. A particular county has a OneToMany relationship to cities and I am trying to make a custom query in the Entity Repository to query a County based on it's ID and return that County and the Cities corresponding to it.
My query currently seems to work great if the county has cities assigned, but if it does not have any cities yet, Doctrine gives me a "Unable to find County entity. " Exception.
I believe there is a logical error in my query, but I am having a hard time re-writing it to return solely the County by ID if no cities are associated with it.
My Query:
class CountyRepository extends EntityRepository
{
public function findOneByIdJoinedToCities($id)
{
$qb = $this->createQueryBuilder('c')
->addSelect('p')
->join('c.cities', 'p')
->where('p.county = :id')
->setParameter('id', $id)
;
$query = $qb->getQuery();
try {
return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e){
return null;
}
}
}
How could I change the above code to still give back a single result for County if no Cities have been assigned to it yet?
Thanks for the help!
Basic SQL question: use a left join. eg:
$qb = $this->createQueryBuilder('c')
->addSelect('p')
->leftJoin('c.cities', 'p')
// ^^^^^^^^
->where('p.county = :id')
->setParameter('id', $id)
;

Count Rows in Doctrine QueryBuilder

I'm using Doctrine's QueryBuilder to build a query, and I want to get the total count of results from the query.
$repository = $em->getRepository('FooBundle:Foo');
$qb = $repository->createQueryBuilder('n')
->where('n.bar = :bar')
->setParameter('bar', $bar);
$query = $qb->getQuery();
//this doesn't work
$totalrows = $query->getResult()->count();
I just want to run a count on this query to get the total rows, but not return the actual results. (After this count query, I'm going to further modify the query with maxResults for pagination.)
Something like:
$qb = $entityManager->createQueryBuilder();
$qb->select('count(account.id)');
$qb->from('ZaysoCoreBundle:Account','account');
$count = $qb->getQuery()->getSingleScalarResult();
Some folks feel that expressions are somehow better than just using straight DQL. One even went so far as to edit a four year old answer. I rolled his edit back. Go figure.
Here is another way to format the query:
return $repository->createQueryBuilder('u')
->select('count(u.id)')
->getQuery()
->getSingleScalarResult();
It's better to move all logic of working with database to repositores.
So in controller you write
/* you can also inject "FooRepository $repository" using autowire */
$repository = $this->getDoctrine()->getRepository(Foo::class);
$count = $repository->count();
And in Repository/FooRepository.php
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->getQuery()
->getSingleScalarResult();
}
It's better to move $qb = ... to separate row in case you want to make complex expressions like
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->where($qb->expr()->isNotNull('t.fieldName'))
->andWhere($qb->expr()->orX(
$qb->expr()->in('t.fieldName2', 0),
$qb->expr()->isNull('t.fieldName2')
))
->getQuery()
->getSingleScalarResult();
}
Also think about caching your query result - http://symfony.com/doc/current/reference/configuration/doctrine.html#caching-drivers
public function count()
{
$qb = $repository->createQueryBuilder('t');
return $qb
->select('count(t.id)')
->getQuery()
->useQueryCache(true)
->useResultCache(true, 3600)
->getSingleScalarResult();
}
In some simple cases using EXTRA_LAZY entity relations is good
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html
If you need to count a more complex query, with groupBy, having etc... You can borrow from Doctrine\ORM\Tools\Pagination\Paginator:
$paginator = new \Doctrine\ORM\Tools\Pagination\Paginator($query);
$totalRows = count($paginator);
Since Doctrine 2.6 it is possible to use count() method directly from EntityRepository. For details see the link.
https://github.com/doctrine/doctrine2/blob/77e3e5c96c1beec7b28443c5b59145eeadbc0baf/lib/Doctrine/ORM/EntityRepository.php#L161
Example working with grouping, union and stuff.
Problem:
$qb = $em->createQueryBuilder()
->select('m.id', 'rm.id')
->from('Model', 'm')
->join('m.relatedModels', 'rm')
->groupBy('m.id');
For this to work possible solution is to use custom hydrator and this weird thing
called 'CUSTOM OUTPUT WALKER HINT':
class CountHydrator extends AbstractHydrator
{
const NAME = 'count_hydrator';
const FIELD = 'count';
/**
* {#inheritDoc}
*/
protected function hydrateAllData()
{
return (int)$this->_stmt->fetchColumn(0);
}
}
class CountSqlWalker extends SqlWalker
{
/**
* {#inheritDoc}
*/
public function walkSelectStatement(AST\SelectStatement $AST)
{
return sprintf("SELECT COUNT(*) AS %s FROM (%s) AS t", CountHydrator::FIELD, parent::walkSelectStatement($AST));
}
}
$doctrineConfig->addCustomHydrationMode(CountHydrator::NAME, CountHydrator::class);
// $qb from example above
$countQuery = clone $qb->getQuery();
// Doctrine bug ? Doesn't make a deep copy... (as of "doctrine/orm": "2.4.6")
$countQuery->setParameters($this->getQuery()->getParameters());
// set custom 'hint' stuff
$countQuery->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, CountSqlWalker::class);
$count = $countQuery->getResult(CountHydrator::NAME);
For people who are using only Doctrine DBAL and not the Doctrine ORM, they will not be able to access the getQuery() method because it doesn't exists. They need to do something like the following.
$qb = new QueryBuilder($conn);
$count = $qb->select("count(id)")->from($tableName)->execute()->fetchColumn(0);
To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:
//in repository class:
$count = $qb->select('count(p.id)')
->from('Products', 'p')
->getQuery()
->getSingleScalarResult();
return $count;
//in controller class:
$count = $this->em->getRepository('RepositoryBundle')->...
return $count-$offset;
Anybody knows more clean way to do it?
Adding the following method to your repository should allow you to call $repo->getCourseCount() from your Controller.
/**
* #return array
*/
public function getCourseCount()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb
->select('count(course.id)')
->from('CRMPicco\Component\Course\Model\Course', 'course')
;
$query = $qb->getQuery();
return $query->getSingleScalarResult();
}
You can also get the number of data by using the count function.
$query = $this->dm->createQueryBuilder('AppBundle:Items')
->field('isDeleted')->equals(false)
->getQuery()->count();

How to use wildcards in createQueryBuilder?

In my repository class i use:
public function getItemsByTag($tag)
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where('c.tags LIKE %bipolar%')
->addOrderBy('c.id');
return $qb->getQuery()
->getResult();
}
But unfortunately this doesn't work.. Anybody knows how this can work? Or do I have to build a custom query without the QueryBuilder?
Thanks!
Searching based on a single parameter:
I think it should go:
public function getItemsByTag($tag)
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where('c.tags LIKE :tag')
->addOrderBy('c.id')
->setParameter('tag', $tag);
return $qb->getQuery()->getResult();
}
But I think that it is discouraged to do a LIKE as part of a where using the query builder so you should do:
$qb = $this->createQueryBuilder('c');
$qb->select('c')
->where($qb->expr()->like('c.tags', '?1'))
->addOrderBy('c.id')
->setParameter(1, $tag);
return $qb->getQuery()->getResult();
Check out the docs for more information, there is an example of a like expression in the section entitled Helper Methods
I should also point out that I used a different convention in each example for passing a parameter into a query, the first used a named parameter :tag which is set by setParameter('tag', $value) the second is just a numbered parameter ?1, you could have just as easily have used a named parameter in the second example if you wished to as well.
Searching with an array of parameters:
You also asked about doing an array of likes. Here it is with an OR expression but if you wanted to search for all tags you could change it to an AND.
In order to make a "LIKE array" you just have to build up the expression on its own.
$qb = $this->createQueryBuilder('c');
$orExpr = $qb->expr()->orX();
for ($i = 0; $i < count($tags); $i++) {
$orExpr->add($qb->expr->like('c.tags', "?$i"));
// You may have to set params later in a loop after $orExpr has been
// added to the queryBuilder.
$qb->setParameter($i, $tags[$i]);
}
$qb->select('c')->where($orExpr)->addOrderBy('c.id');
return $qb->getQuery()->getResult();
If you don't want to substitute your query with variables but use a static string you have to put the string in apostrophes.
You have to use apostrophes instead of quotes! Otherwise the Doctrine2 Lexer will throw an Exception.
So in your case Mike you can use:
'c.tags LIKE \'%bipolar%\''
or
"c.tags like '%bipolar%'"
I don't know much about Symfony, but based on what I know about PHP and MySQL, I imagine you mean 'c.tags LIKE "%bipolar%"'. You likely need quotation marks around %bipolar%.
simply:
public function getItemsByTag($tag)
{
$qb = $this->createQueryBuilder('c')
->select('c')
->where( $qb->expr()->like('c.tags', ':tags') )
->addOrderBy('c.id');
$qb->setParameter('tags', '%' . $tag . '%' );
return $qb->getQuery()->getResult();
}

Resources