Symfony2 / Doctrine2 - How to convert this SQL request with QueryBuilder?

♀尐吖头ヾ 提交于 2020-01-06 07:04:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!