Symfony Doctrine if statement in querybuilder - php

Is it possible to insert IF statement inside doctrine query builder? For example: I have User and Group entities with OneToMany relationship. Group has boolean field hidden. How to create query builder which would select groups that are hidden = false if Group owner is not current user. So that only group owner can see hidden=true groups. and other users can only see hidden=false groups
$qb = $this->createQueryBuilder('group')
->where('group.owner = :userId')
->setParameter('userId', $user->getId())
->orderBy('group.created', 'DESC');

This should fit your needs
$qb = $this->createQueryBuilder('group');
$qb
->where(
$qb->expr()->andX(
$qb->expr()->eq('group.owner', ':userId'),
$qb->expr()->eq('group.hidden', true)
)
)
->orWhere($qb->expr()->eq('group.hidden', false))
->setParameter('userId', $user->getId())
->orderBy('group.created', 'DESC');
First part of query will keep a row only if current user is the owner and group is hidden.
Second part will include all non-hidden groups.

Related

How to use IF statement in Doctrine Query Builder select

I have a doctrine statement to get all the fields from a table
->createQueryBuilder()
->select('u')
->from(User::class, 'u')
How can I add to this select an additional column based on a value in another column? This would be the mysql equivalent:
SELECT
u.*,
IF(u.group = 1, 'Yes', 'No') as isAdmin
FROM user u ...
I need to know how to do this in doctrine. Thanks.

Transpose a raw SQL query with doctrine

I'm pretty new to Doctrine ORM and I'm trying to transform a raw SQL query with doctrine to get an array of Entities.
Basically I want to get one of more course entities where a user is indirectly registered. The course id is in a traineeship table. The traineeship id and the user id are in a registration table.
Here's my SQL query :
SELECT * FROM course c
LEFT JOIN traineeship t
ON c.id = t.courseId
LEFT JOIN registration r
ON t.id = r.traineeshipId
WHERE r.userId = 2681;
Here's what I try to do with doctrine :
return $this->createQueryBuilder('c')
->andWhere('t.course = c')
->leftJoin('c.traineeships', 't')
->andWhere('r.traineeship = t')
->leftJoin('t.registrations', 'r')
->andWhere('r.id = :user')
->setParameter('user', $user)
->getQuery()
->execute();
With my raw SQL query, I get two expected results with a given id. With the generated query by doctrine, I get only one result. So I guess my doctrine use is bad.
(Doctrine relations :
Course OneToMany Traineeship
Traineeship OneToMany Registration
Registration ManyToOne User)
From the raw SQL I would expect the following query:
return $this->createQueryBuilder('c')
->leftJoin('c.traineeships', 't')
->leftJoin('t.registrations', 'r')
->andWhere('r.user = :user')
->setParameter('user', $user)
->getQuery()
->getResult();
Please note that I'm using ->andWhere('r.user = :user') instead of ->andWhere('r.id = :user') as I assume that registration.id holds the id of the registration but not the id of the user. In my query I furthermore assume that registration has an attribute user which holds a reference to the user.
The query should return an array of course entities.

Order By on Joined Entity - Doctrine Query Builder

I have the following query:
$qb = $this->_em->createQueryBuilder();
$qb->select('a')
->from('CatalogueBundle\Entity\Avantage','a')
->leftJoin('a.avantagegrilles', 'g')
...
->orderBy('a.avantageOrdre', 'ASC');
The result of the query is as follows:
An avantage can contain several avantagegrilles. Now there is a variable in entity avantagegrille called avantagegrilleMini and I want to do an order by asc on it; that is, when an avantage is returned, its avantagegrilles are ordered according to their avantagegrilleMini.
I added ->orderBy('g.avantagegrilleMini', 'ASC') to the query but it didn't have any effect. Is what I want to implement possible in Doctrine?
Let's try this line: ->orderBy('g.avantageOrdre', 'ASC');

How to make a join query on Symfony with Doctrine?

I'm kinda stuck on using the querybuilder to create a join query.
There is a table called "Person" and a table called "Vacancy". If a person is linked to the vacancy the person.id and vacancy.id is saved in a table called "Candidacy". So how do I get all the persons who are linke to vacancy.id 1?
So where do I have to initiate the AppBundle:Candidacy entity?
$entity = $em
->getRepository('AppBundle:Person')
->createQueryBuilder('p')
->join('p.id', 'c')
->where('c.vacancyId= 1')
->getQuery()
->getResult();
Thank you in advance.
Example in your repository :
public function getPersonVacancy($personId) {
$qb = $this->createQueryBuilder('p');
$qb->leftJoin('p.vacancy', 'v');
$qb->select('v.name', 'v.id');
$qb->where('p.id = :personId');
$qb->setParameter('personId', $personId);
return $qb ->getQuery()->getResult();
This is to give you an example it may not work with copy paste.
Also, all join methods are explained in doctrine documentation, feel free to read it http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html
Looks like you have many-to-many relation.
You should link your Person and Vacancy table through Candidacy to Person and then Vacancy to Candidacy.
small example: Entity User is attached to Engagement via UserEngagement table.
$qb = $this->_em->createQueryBuilder()
->select('u')
->from($this->_entityName, 'u')
->join('u.userEngagements', 'ue')
->join('ue.engagement', 'en')
...

Doctrine2 get object without relations

An user has one role.
A role has zero or many users.
I would like to find roles without users.
I need to have this query without using IN or NOT IN
I tried with join:
$qb = $this->createQueryBuilder('role');
$qb
->leftJoin('role.users', 'users')
->where('users IS NULL')
without join
$qb = $this->createQueryBuilder('role');
$qb
->where('role.users IS NULL')
with id:
$qb = $this->createQueryBuilder('role');
$qb
->leftJoin('role.users', 'users')
->where('users.role != role')
Do you have other ideas? Do I have no other choices than to use IN / NOT IN queries?
Thanks in advance
You can find roles that don't have any users by using a count query
$qb = $this->createQueryBuilder('role');
$qb ->addSelect('COUNT(users.id) AS total_users')
->leftJoin('role.users', 'users')
->groupBy('role.id')
->having('total_users = 0')
->getQuery()->getResult();

Categories