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.
Related
This is my function where I'm trying to show the User history. For this I need to display the user's current credits along with his credit history.
This is what I am trying to do:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb->select(array('a','u'))
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('User\Entity\User', 'u', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.user = u.id')
->where("a.user = $users ")
->orderBy('a.created_at', 'DESC');
$query = $qb->getQuery();
$results = $query->getResult();
return $results;
}
However, I get this error :
[Syntax Error] line 0, col 98: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Edit: I replaced 'ON' with 'WITH' in the join clause and now what I see is only 1 value from the joined column.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
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();
subquery and querybuilder in my project
but when use ```IFNULL`` command in query return eroor
my code is bellow
$subQb = $em->createQueryBuilder();
$subquery = $subQb->select('COUNT(v.id)')
->from('AdminBundle:Visitsite', 'v')
->where('v.site = s.id')
->Andwhere('v.createdate > :date')
->getDQL();
$subQb2 = $em->createQueryBuilder();
$subquery2 = $subQb2->select('l.quantity')
->from('AdminBundle:Limitviewday', 'l')
->where($subQb2->expr()->eq('s.limitviewday', 'l.id'))
->getDQL();
$subQb3 = $em->createQueryBuilder();
$subquery3 = $subQb3->select('COUNT(i.id)')
->from('AdminBundle:Visitsite', 'i')
->where('i.id = s.id')
->Andwhere('i.createdate > :date2')
->Andwhere('i.ip = :ip')
->groupBy('i.ip')
->getDQL();
$subQb4 = $em->createQueryBuilder();
$subquery4 = $subQb4->select('ipl.quantity')
->from('AdminBundle:Iplimitview', 'ipl')
->where('s.iplimitview = ipl.id')
->getDQL();
$qb = $em->createQueryBuilder();
$query = $qb->select('s')
->from('AdminBundle:Sites', 's')
->where('s.quantity > :one')
->Andwhere('s.status = :two')
->Andwhere($qb->expr()->lt("($subquery)", "($subquery2)"))
->Andwhere($qb->expr()->lt("(SELECT IFNULL( ($subquery3),0) )", "($subquery4))"))
->setParameter('one', 1)
->setParameter('two', 1)
->setParameter('date', $date->format('Y-m-d'))
->setParameter('ip', $ip)
->setParameter('date2', $date->format('Y-m-d 00:00:00'));
and my result is
[Syntax Error] line 0, col 274: Error: Expected known function, got
'IFNULL'
Doctrine has limited set of mapped functions, and seems it has no IFNULL by default.
The simple way is to change your DQL and replace IFNULL with IF or COALESCE.
The more difficult way is read manual and implement your own IFNULL mapping like this
I try to convert this query to the querybuilder:
SELECT *, landingpages_content.id as cid FROM `landingpages_content` LEFT JOIN content ON landingpages_content.content_id = content.id WHERE content.enabled = 1 AND landingpages_content.landingpage_id = ? ORDER BY landingpages_content.`order`
This is my QueryBuilder code:
$queryBuilder
->select('*, landingpages_content.id as cid')
->from('landingpages_content', 'landingpages_content')
->leftJoin('landingpages_content.content_id', 'content.id', null)
->where('content.enabled = 1')
->andWhere('landingpages_content.landingpage_id = :id')
->setParameter('id', $id)
->orderBy('landingpages_content.`order`', 'ASC');
It returns
InvalidArgumentException: The query builder cannot have joins.
You are using leftJoin method wrong. Try something like this:
$queryBuilder
->select('*, landingpages_content.id as cid')
->from('landingpages_content', 'landingpages_content')
->leftJoin('landingpages_content.content', 'content', 'ON', 'landingpages_content.content_id = content.id')
->where('content.enabled = 1')
->andWhere('landingpages_content.landingpage_id = :id')
->setParameter('id', $id)
->orderBy('landingpages_content.order', 'ASC');
This is my function where I'm trying to show the User history. For this I need to display the user's current credits along with his credit history.
This is what I am trying to do:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb->select(array('a','u'))
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('User\Entity\User', 'u', \Doctrine\ORM\Query\Expr\Join::WITH, 'a.user = u.id')
->where("a.user = $users ")
->orderBy('a.created_at', 'DESC');
$query = $qb->getQuery();
$results = $query->getResult();
return $results;
}
However, I get this error :
[Syntax Error] line 0, col 98: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Edit: I replaced 'ON' with 'WITH' in the join clause and now what I see is only 1 value from the joined column.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)