简体   繁体   English

Symfony原则if querybuilder中的if语句

[英]Symfony Doctrine if statement in querybuilder

Is it possible to insert IF statement inside doctrine query builder? 是否可以在理论查询生成器中插入IF语句? For example: I have User and Group entities with OneToMany relationship. 例如:我有具有OneToMany关系的UserGroup实体。 Group has boolean field hidden . 组具有hidden布尔字段。 How to create query builder which would select groups that are hidden = false if Group owner is not current user. 如果Group所有者不是当前用户,如何创建查询构建器以选择hidden组= false。 So that only group owner can see hidden=true groups. 这样,只有群组所有者才能看到hidden = true群组。 and other users can only see hidden=false groups 而其他用户只能看到hidden = false组

 $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. 第二部分将包括所有非隐藏组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM