How to use IF statement in Doctrine Query Builder select - php

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.

Related

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 calculated fields in Doctrine QueryBuilder

I have the following fields in one of my entities: price(decimal), promo(boolean), and promoPrice(decimal) and I want to get query with order by real price, so I need to create query like this one:
SELECT *, (!promo*price + promo*promo_price) as real_price
FROM `product` ORDER BY real_price ASC
Is there any way to do it with QueryBuilder or maybe I need to use some native methods?
SOLUTION:
$repository = $this->getDoctrine()->getRepository('AppBundle:Product');
$query = $repository->createQueryBuilder('p')
->addSelect('CASE WHEN p.promo = :value THEN p.promoPrice ELSE p.price END AS HIDDEN realPrice')
->setParameter('value', true)
->orderBy('realPrice', 'ASC')
->getQuery();

Symfony Doctrine if statement in querybuilder

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.

querybuilder join query in Doctrine2 for Symfony2

Could somebody convert this query for me in querybuilder?
SELECT m.id,n.unitid
FROM mappaths m JOIN unitids n on (m.id=n.id) where n.databaseid=1
I am using this query but it gives me all the values of mm.unitid, while my requirement is to get only one value that is defined by test=1 variable
$query=$qb->select('mm.unitid')
->from('ApiMapBundle:Mappaths','m')
->from('ApiMapBundle:Unitids','mm')
// ->leftJoin('m','u')
->leftJoin('m.refUnitids1','u','WITH','m.id = u')
// ->leftJoin('m.refUnitids2','v')
->where('m.id=:test')
->setParameter('test',1)
->getQuery()->getResult();
Try following:
$query = $qb->select('mm.unitid')
->from('ApiMapBundle:Mappaths','m')
->innerJoin('m.refUnitids1','mm','WITH','m.id = mm.FIELD') //you need to specify on which field of mm join should be done
->where('m.id=:test')
->setParameter('test',1)
->getQuery()
->getResult();
You need to specify field of Unitids which should be used to join to Mappaths. The best way would be to define this relation in Entity definition, then you can use just ->innerJoin('m.refUnitids1','mm') without additional join parameters.
Also, in this case, it is better to use innerJoin instead of leftJoin

How to set a where clause filter with doctrine2 query buider in a many-to-many relation

I've been trying with no success to user doctrine2 query builder to fetch records in a related many-to-many table using a where clause.
I would like to reproduce the following statement:
SELECT [...] FROM Company
JOIN CompanyAddress ON CompanyAddress.CompanyId = Company.Id
JOIN Address ON Address.Id = CompanyAddress.AddressId
WHERE Address.State = ?
following some ideias found on google, stackoverfow and doctrine docs:
$qb = $this->_em->createQueryBuilder();
$qb->select('c')
->from('Company', 'c')
->where(':State MEMBER OF c.Address')
->setParameter('State', $arguments);
but the results are not the desired one. Any help? Thanks..

Categories