DQL Subquery Questions - php

I'm trying to SLECT * FROM a table o where the vendor is what I pass.(this is in the context of a Doctrine Repository). I then want to run a subquery and SELECT * FROM AppBundle:PriceOption where p.offer is o. I'm getting a QueryException when running this code though:
public function getVendorFeaturedDeals(Vendor $vendor){
$purchaseOptions = $this->
getEntityManager()
->createQueryBuilder()
->from('AppBundle:PriceOption', 'p')
->innerJoin('p.offer', 'o')
->getDQL();
$query = $this->createQueryBuilder('o');
return $query
->where('o.vendor = :vendor')
->addSelect(sprintf('(%s)', $purchaseOptions))
->setParameter(':vendor', $vendor)
->getQuery()
->execute();
}
Here's the error : AppBundle\Tests\Service\VendorServiceTest::testGetVendorFeaturedDeals
Doctrine\ORM\Query\QueryException: [Syntax Error] line 0, col 18: Error: Unexpected 'FROM' Caused by Doctrine\ORM\Query\QueryException: SELECT o, (SELECT FROM AppBundle:PriceOption p INNER JOIN p.offer o) FROM AppBundle\Entity\Offer o WHERE o.vendor = :vendor
Any help would be appreciated, thanks!

You should modify your query to:
$purchaseOptions = $this->
getEntityManager()
->createQueryBuilder()
->select(['p', 'o'])
->from('AppBundle:PriceOption', 'p')
->innerJoin('p.offer', 'o')
->getDQL();

Related

Symfony subquery with getDQL throws error

I am trying to convert below query
SELECT * FROM (SELECT * FROM table_name d WHERE d.number != '' ORDER BY d.stop_time DESC ) AS p GROUP BY p.number
with symfony query builder as below =>
$sub = $this->entityManager->createQueryBuilder();
$sub->select('d')
->from($this->entityManager->getClassMetadata($entityClass)->getName(), 'd')
->where("d.number != ''")
->orderBy('d.time', 'DESC');
$qb = $this->entityManager->createQueryBuilder();
$qb->select('p')
->from($sub->getDQL(),'p')
->groupBy('p.number');
I am getting below error =>
[Syntax Error] line 0, col 14: Error: Expected Doctrine\ORM\Query\Lexer::T_ALIASED_NAME, got 'SELECT'
Please correct query if anything wrong in it.
Here is answer
$sub = $this->entityManager->createQueryBuilder();
$sub->select('d.id')
->from($this->entityManager->getClassMetadata($entityClass)->getName(), 'd')
->where("d.number != ''")
->orderBy('d.time', 'DESC');
$qb = $this->entityManager->createQueryBuilder();
$qb->select('p')
->from($this->entityManager->getClassMetadata($entityClass)->getName(), 'p')
->where("p.id IN (".$sub->getDQL().")")
->groupBy('p.number');

Doctrine2 - double left join query issue

I am using Symfony v3.4 branch with Doctrine.
I am having trouble translating SQL query to Doctrine ORM query.
I have 3 tables.
Shop
Firm
User
User --> 1:1 --> Firm --> 1:1 --> Shop
(Symfony developer tool bar reports that associations in tables are made correctly).
I want to get Shop data that corresponds to cretain User in one query.
My SQL, that get a result:
SELECT *
FROM mp2_fos_user as u
LEFT JOIN mp2_firm AS f ON u.id = f.firmUserId
LEFT JOIN mp2_shop AS s ON f.id = s.shopFirmId
WHERE u.id = 1
My Doctrine ORM query
$query = $em->createQueryBuilder()
->select('u, f, s')
->from('App:User', 'u')
->leftJoin('u.userFirm WITH u.id = f.firmUserId', 'f')
->leftJoin('f.firmShop WITH f.id = s.shopFirmId', 's')
->where('u.id = :user_id')
->setParameter('user_id', $user_id)
->getQuery();
at the moment running the code results in an error
[Syntax Error] line 0, col 57: Error: Expected end of string, got 'u'
What would be best practice for my issue?
Help would be much appreciated,
Thank you!
UPDATE
tried:
$query = $em->createQueryBuilder()
->select('s.id')
->from('App:User', 'u')
->leftJoin('u.userFirm WITH f.firmUser = u', 'f')
->leftJoin('f.firmShop WITH s.shopFirm = f', 's')
->where('u.id = :user_id')
->setParameter('user_id', $user_id)
->getQuery();
got [Syntax Error] line 0, col 54: Error: Expected end of string, got 'f'
There is no need to use WITH clause if you have defined mapping in your entities, WITH clause is used when you want to join your entities with additional matching criteria
class User
{
/**
* #ORM\YourRelationShipNature(targetEntity="App\Entity\Firm", mappedBy="user")
*/
private $userFirm;
}
class Firm
{
/**
* #ORM\YourRelationShipNature(targetEntity="App\Entity\Shop", mappedBy="firm")
*/
private $firmShop;
}
class Shop
{
//.....
}
And then your could simple use properties to join your entites
$query = $em->createQueryBuilder()
->select('u, f, s')
->from('App:User', 'u')
->leftJoin('u.userFirm', 'f')
->leftJoin('f.firmShop', 's')
->where('u.id = :user_id')
->setParameter('user_id', $user_id)
->getQuery();
I was thinking of something more along the lines of this (assuming the entity names are correct):
$query = $em->createQueryBuilder()
->select('u, f, s')
->from('App:User', 'u')
->leftJoin('App:UserFirm f WITH f.firmUser = u')
->leftJoin('App:FirmShop s WITH s.shopFirm = f')
->where('u.id = :user_id')
->setParameter('user_id', $user_id)
->getQuery();

CreateQuery Doctrine Symfony 2 StateFieldPathExpression

I have this Query in MySql
SELECT l.id as like_id, l.spotted_id as spotted_id,count(l.spotted_id) as numero_likes
FROM sn_like_spotted l
LEFT JOIN prof_foto f
ON f.id = l.spotted_id
LEFT JOIN sn_profilo p
ON f.profilo_id = p.id
WHERE p.id = 3
GROUP BY l.spotted_id
ORDER BY numero_likes DESC LIMIT 0,10
I try to do this in Doctrine
public function getFoo($profilo_id){
$em = $this->getEntityManager();
$query = $em->createQuery('
SELECT l.id as like_id, l.spotted_id as spotted_id,count(l.spotted_id) as numero_likes
FROM SNLikeBundle:LikeSpotted l
LEFT JOIN SNFotoBundle:Foto f
WITH f.id = l.spotted_id
LEFT JOIN SNProfiloBundle:Profilo p
WITH f.profilo_id = p.id
WHERE p.id = :profilo_id
GROUP BY l.spotted_id
ORDER BY numero_likes DESC
')->setFirstResults(0)
->setMaxResults(10)
->setParameter('profilo_id', $profilo_id);
$results = $query->getResult();
return $results;
}
Then i have this error
[Semantical Error] line 0, col 36 near 'spotted_id as': Error: Class SN\LikeBundle\Entity\LikeSpotted has no field or association named spotted_id
I change SELECT in:
SELECT l.id as like_id, l.spotted as spotted_id,count(l.spotted) as numero_likes
and I have this Error:
[Semantical Error] line 0, col 36 near 'spotted as spotted_id,count(l.spotted)': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
Then i Try With IDENTITY
SELECT IDENTITY l.id as like_id, l.spotted as spotted_id,count(l.spotted) as numero_likes
But i Have This Error
[Syntax Error] line 0, col 26: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '.'
I try to create also in QueryBuilder (more criteria, same result)
$q = $this->createQueryBuilder('l');
$q->leftJoin("l.spotted", 's');
$q->leftJoin("s.profilo", 'p');
$q->leftJoin("p.utente", 'u');
$q->where('(s.foto_eliminata IS NULL OR s.foto_eliminata != 1)');
$q->andWhere('p.fase_registrazione = :fase');
$q->andWhere('u.locked = :false');
$q->andWhere('p.id = :profilo_id');
$q->setParameter(':fase', 100);
$q->setParameter('false', false);
$q->setParameter('profilo_id', $profilo_id);
$q->groupBy('l.spotted');
$q->orderBy($q->expr()->count('l.spotted'), 'desc');
$q->setMaxResults(10);
$dql = $q->getQuery();
$results = $dql->execute();
return $results;
My error is
[Syntax Error] line 0, col 285: Error: Expected end of string, got '('
The problem is in
$q->orderBy($q->expr()->count('l.spotted'), 'desc');
For CreateBuilder Case I Resolved:
$q = $this->createQueryBuilder('l');
$q->addSelect('count(l.spotted) as numero_likes');
$q->leftJoin("l.spotted", 's');
$q->leftJoin("s.profilo", 'p');
$q->leftJoin("p.utente", 'u');
$q->where('(s.foto_eliminata IS NULL OR s.foto_eliminata != 1)');
$q->andWhere('p.fase_registrazione = :fase');
$q->andWhere('u.locked = :false');
$q->andWhere('p.id = :profilo_id');
$q->setParameter(':fase', 100);
$q->setParameter('false', false);
$q->setParameter('profilo_id', $profilo_id);
$q->groupBy('l.spotted');
$q->addOrderBy('numero_likes','DESC');
$q->setMaxResults(10);
$dql = $q->getQuery();
$results = $dql->execute();
return $results;
if i don't want numero_likes in my results i can do this:
$q->addSelect('count(l.spotted) as HIDDEN numero_likes');
But i'd like how can i do this in createQuery

Subquery in doctrine2 notIN Function

I'd like to select members who are not in specific service. I have 3 tables :
membre
service
membre_service (relation between membre and service)
I'm using doctrine 2 and in SQL my query is :
SELECT m.* FROM membre m WHERE m.`id` NOT IN (
SELECT ms.membre_id FROM membre_service ms WHERE ms.service_id != 29
)
In Doctrine, I do :
$qb = $this->_em->createQueryBuilder();
$qb2 = $qb;
$qb2->select('m.id')
->from('Custom\Entity\MembreService', 'ms')
->leftJoin('ms.membre', 'm')
->where('ms.id != ?1')
->setParameter(1, $service);
$qb = $this->_em->createQueryBuilder();
$qb->select('m')
->from('Custom\Entity\Membre', 'm')
->where($qb->expr()->notIn('m.id', $qb2->getDQL())
);
$query = $qb->getQuery();
//$query->useResultCache(true, 1200, __FUNCTION__);
return $query->getResult();
I got the following error :
Semantical Error] line 0, col 123 near 'm WHERE ms.id': Error: 'm' is already defined.
The same alias cannot be defined 2 times in the same query
$qb = $this->_em->createQueryBuilder();
$qb2 = $qb;
$qb2->select('m.id')
->from('Custom\Entity\MembreService', 'ms')
->leftJoin('ms.membre', 'm')
->where('ms.id != ?1');
$qb = $this->_em->createQueryBuilder();
$qb->select('mm')
->from('Custom\Entity\Membre', 'mm')
->where($qb->expr()->notIn('mm.id', $qb2->getDQL())
);
$qb->setParameter(1, $service);
$query = $qb->getQuery();
return $query->getResult();
Ideally you should use many-to-many relation for your entity, in this case your query is going to be much simpler.
Actually if you are using the Symfony2 repository class you could also do the following:
$in = $this->getEntityManager()->getRepository('Custom:MembreService')
->createQueryBuilder('ms')
->select('identity(ms.m)')
->where(ms.id != ?1);
$q = $this->createQueryBuilder('m')
->where($q->expr()->notIn('m.id', $in->getDQL()))
->setParameter(1, $service);
return $q->getQuery()->execute();
You can use (NOT) MEMBER OF:
<?php
$query = $em->createQuery('SELECT m.id FROM Custom\Entity\Membre WHERE :service NOT MEMBER OF m.services');
$query->setParameter('service', $service);
$ids = $query->getResult();
See the documentation for more examples.

Doctrine2 Multiple Join works with createQuery but not with queryBuilder

If I'm using querying without queryBuilder with this dql
$query = $this->_em
->createQuery("SELECT p, g, c
FROM LikeYeah\GoBundle\Entity\Product p
JOIN p.garments g
LEFT JOIN g.colours c
ORDER BY p.id DESC
");
everything is fine, but if I use the (what I belive is the same) query trough query builder like this
$qb->select('p, g, c')
->from('LikeYeah\GoBundle\Entity\Product', 'p')
->join('p.garments', 'g')
->leftJoin('g.colours', 'c')
->orderBy('p.id', 'desc');
I get the following error:
"Semantical Error] line 0, col 66 near '.colours c, LikeYeah\GoBundle\Entity\Product': Error: Identification Variable g used in join path expression but was not defined before."
What am I missing?
Try this: using addSelect after your joins:
$qb->select('p')
->join('p.garments', 'g')
->addSelect('g')
->from('LikeYeah\GoBundle\Entity\Product', 'p')
->join('p.garments', 'g')
->leftJoin('g.colours', 'c')
->addSelect('c')
->orderBy('p.id', 'desc');
You can help from this method
public function findSampleClothingTypeGender($gender) {
$query = $this->getEntityManager()
->createQuery('
SELECT p FROM Acme:Product p
JOIN p.clothing_type ct
WHERE p.gender = :gender'
)->setParameter('gender', $gender);
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}
Try with below one
$qb->select('p','g','c')
->from(array('LikeYeah\GoBundle\Entity\Product','p'))
->join(array('p.garments','g'))
->join(array('g.colours','c'),'LEFT')
->order_by('p.id','DESC');
may be try
$qb->select('p, g, c')
->from('GoBundle:Product', 'p')
->join('p.garments', 'g')
->leftJoin('g.colours', 'c')
->orderBy('p.id', 'desc');
show your $qb init and DQL result
It works for me.
$this->_em->createQueryBuilder()
->select('fu,e,t')
->from('\xxxx\AdminBundle\Entity\FrontUser','fu')
->join('fu.read_essays','e')
->leftJoin('e.tags','t')
->getQuery()->execute();
I think you should create a new QueryBuilder object.
You can use follow code to see Dql of that QueryBuilder
$qb->getDQL();

Categories