Symfony QueryBuilder andWhere for User-Relation not Working - symfony

I want to load items for a given User. Between Item and User lives a One-To-Many relationship.
If I use the following, everything is working well:
$result = $em→getRepository(Item::class)→findBy(['user' => $user]);
The $result has 3 entries.
Now I have to give additional conditions to the query. So I want to use the queryBuilder insight the repository:
$result = $this->createQueryBuilder('i')
->andWhere('i.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
The result is empty but the query runs without any errors.
Can someone tell me what I'm doing wrong?
In both cases the $user is the related App\Entity\User entity.

I found the solution. It didn't work because of the Uuid. This works:
$result = $this->createQueryBuilder('i')
->andWhere('i.user = :user')
->setParameter('user', $user->getId()->toBinary())
->getQuery()
->getResult();

Related

Doctrine QueryBuilder leftJoin + MEMBER OF fails to work

This piece of code failse to produce the correct results:
$queryBuilder
->leftJoin(sprintf('%s.building', $rootAlias), 'building')
->andWhere(':user MEMBER OF building.owners OR :user MEMBER OF building.managers')
->setParameter('user', $user);
whereas this returns a correct result:
$queryBuilder
->leftJoin(sprintf('%s.building', $rootAlias), 'building')
->andWhere('building.id = :id')
->setParameter('id', 1);
$user is properly defined and member of building.managers.
It was a caching issue apparently. The above code works.

DQL query ManyToMany IN

This query in not working. What could be wrong? Post has author(User entity). User has Following(ManyToMany self-directing)
I'm trying to get all Posts of the Users which I'm following
$userId = $this->getUser()->getId();
$qb = $em->createQueryBuilder();
$qb2 = $qb;
$qb2 = $em->createQueryBuilder()
->select('u.following')
->from('AppBundle\Entity\User', 'u')
->where('u.id = :userId');
$qb->select('p')
->from('AppBundle\Entity\Post', 'p')
->where($qb->expr()->In('p.author', $qb2->getDQL()));
$qb->setParameter('userId', $userId);
$dql = $qb->getDQL();
I will assume that your code is in repository as it should be...
src/AppBundle/Controller/PostController.php
$em=$this->getDoctrine()->getManager();
$myResultCollection=$em->getRepository(Post::class)->myCustomQuery($this->getUser());
src/AppBundle/Repository/PostRepository.php
public function myCustomQuery(User $user) {
$em=$this->getEntityManager();
$qb=$em->createQueryBuilder();
return $qb->select("p")
->from(Post::class, "p")
->where($qb->expr()->in("p.author",
$qb->select("u.following")
->from(User::class, "u")
->where("u.id=:USERID")
->getDQL()))
->setParameters(array('USERID'=>$user->getId()))
->getQuery()
->execute();
}
As side note, you should be careful with quotes.
Make sure to use double quotes when using DQL (it's true for SQL too).
The reason is because you need simple quote for strings in queries.

doctrine query onetonmany / notIn with objects / symfony forms querybuilder

I am using symfony 2 and doctrine to prefilter a form field type 'entity' with the help of a querybuilder.
My querybuilder should return all products which the user has not already added to a list.
All relations are bidirectionnal.
I have products linked to userIngredients (oneToMany) each linked to one user (manyToOne)
I have come with this so far but it's not working, I get products not added by other users.
return $this
->createQueryBuilder('p')
->leftJoin('p.userIngredients', 'i')
->where('i.user <> ?1')
->setParameter(1,$user);
1; Any clue on how to correct this ?
Alternatively, I could select the products I don't want and then reselect those who don't match but using an expression and NotIn seems to only work for strings
$products = $this
->createQueryBuilder('p')
->leftJoin('p.userIngredients', 'i')
->where('i.user = ?1')
->setParameter(1,$user)
->getQuery()
->getResult();
return $this
->createQueryBuilder('p')
->where($this->createQueryBuilder('p')->expr()->notIn('p', $products));
2; how could we correct this to make it work with objects ?
3; alternatively : is there a way to pass not a querybuilder but an array of results to symfony form builders ?
I got thinks thanks to Javad:
(slight modification, I'm using an array result, not dql):
$qb = $this->_em->createQueryBuilder();
$ids = $qb
->select('p.id')
->from('AppBundle:MarketPlace\Product','p','p.id')
->leftJoin('p.userIngredients', 'i')
->where('i.user = ?1')
->setParameter(1,$user)
->getQuery()
->getResult();
//I don't know why I couldn't directly get an array of ids otherwise... if you know how to do better directly from the query, I'm interested (getScalarResult does not make it)
$ids=array_keys($ids);
$result = $this
->createQueryBuilder('p')
->where($this->createQueryBuilder('p')->expr()->notIn('p.id', $ids));
return $result;

doctrine how to fetch database switch a datetime

I can't find the answer in the documentation.
I use symfony for an application, i have a database with a datetime for each of my table and would like to get only the row with the most recent datetime is there a function like $repository->findOneById($id) to obtain this object ?
Here is a solution using QueryBuilder:
$repository = $this->getDoctrine()
->getRepository('AcmeStoreBundle:Product');
$query = $repository->createQueryBuilder('p')
->orderBy('p.datetime', 'DESC')
->setMaxResults(1)
->getQuery();
$product = $query->getResult();
Regards.

Doctrine2 findOneBy argument equivalent to BETWEEN in SQL

I need to be able to use the following WHERE clause in Doctrine:
WHERE AL.UserID = 41 AND (TheDate BETWEEN DATE_SUB(CURDATE(), INTERVAL 2 WEEK) AND CURDATE())
and what I'm currently doing is:
$results = $em->getRepository('MyBundle:MyTable')->findOneBy(array('userId' => $userId));
However, I haven't been able to filter results by the last 2 weeks without writing SQL or DQL.
Is there any way I can achieve this through Doctrine's methods?
You can use QueryBuilder. Assuming you are using MySQL BETWEEN, something like:
<?php
// $em instanceof EntityManager
$qb = $em->createQueryBuilder();
$now = new DateTime();
$qb->select('c')
->from('MyClass', 'c')
->where($qb->expr()->andX(
$qb->expr()->eq('c.UserID', '?1'),
$qb->expr()->gte('c.TheDate', '?2'),
$qb->expr()->lte('c.TheDate', '?3')
))
->setParameter(1, 41)
->setParameter(2, $now.sub(new DateInterval('P2W')))
->setParameter(3, $now);
$query = $qb->getQuery();
$c = $query->getSingleResult();
This is cleaner code and should work across the different database platforms supported by Doctrine2 ORM.

Resources