问题
I have a relation : User -> [OneToMany] -> Profile <- [OneToMany] <- Group
When a user joins a group, a profile is created with the couple user_id/group_id.
And I want to get the unjoined groups from a user.
This SQL request work good, but I want to translate it with QueryBuilder :
For the user with id 2,
SELECT g.id
FROM Group g
WHERE id NOT IN (SELECT group_id FROM Profile WHERE user_id = 2)
Thanks for your help.
回答1:
I didn't test it, but I think this should work
$qb = $this->conn->createQueryBuilder();
$qb->select('g.id');
$qb->from('Group', 'g');
$qb->innerJoin('g', 'Profile', 'p', 'g.id != p.group_id');
$qb->where('p.group_id = 2);
**edit Sorry i didn't read the unjoined part.
Try this
$qb = $this->conn->createQueryBuilder();
$qb->select('g.id');
$qb->from('Group', 'g');
$qb->where($qb->expr()->notin(
'g.id',
$qb2->select('p.group_id')
->from('Profile', 'p')
->getDQL()
));
来源:https://stackoverflow.com/questions/15023195/symfony2-doctrine2-how-to-convert-this-sql-request-with-querybuilder