简体   繁体   English

Symfony2 / Doctrine:使用OneToMany基数来查找

[英]Symfony2 / Doctrine : findBy with OneToMany cardinality

I would like to if it possible (and how) to use a OneToMany relationship cardinality as findBy filter. 我想是否有可能(以及如何)将OneToMany关系基数用作findBy过滤器。

For instance here, let's say I have two entities User and Post with a OneToMany relationship between them so that an user has a collection of posts. 例如,在这里,我有两个实体UserPost ,它们之间具有OneToMany关系,这样一个用户就有了一个帖子集合。

I am looking for a way to get all users that have at least one post, that is to say : 我正在寻找一种方法来获取所有至少发布一个帖子的用户,也就是说:
|user.posts| >= 1 |user.posts| >= 1 or more programmatically count(user->getPosts()) >= 1 |user.posts| >= 1或更多以编程方式count(user->getPosts()) >= 1

I know this can be achieved with a QueryBuilder or DQL but I am quite sure there is a trick that allows to make it work with findBy . 我知道可以使用QueryBuilder或DQL来实现,但是我很确定有一个技巧可以使它与findBy一起findBy

Here is the idea of what I am willing to do : 这是我愿意做的事情:

class UserRepository extends EntityRepository
{
    public function myQuery()
    {
        return $this->findBy(
            array(... 'posts' ...), // What should I put here ?
            array('email' => 'ASC')
        );
    }
}

People in the comments are completely right, so I'm summing up: 评论中的人是完全正确的,所以我总结一下:

  • findBy won't work on a OneToMany , particularly since you want to find by the number of related entities. findBy不适用于OneToMany ,尤其是因为您findBy相关实体的数量进行查找。

  • This means you have to use a QueryBuilder . 这意味着您必须使用QueryBuilder

In your UserRepository , use the following: 在您的UserRepository ,使用以下命令:

$qb = $this->createQueryBuilder('users')
    ->leftJoin('user.posts', 'posts')
    ->addGroupBy('users')
    ->having('COUNT(posts) >= :limit')
    ->setParameter('limit', 1);
  • Since in your use case, the limit of Posts you want to select is 1, as said @Yoshi, you can use INNER JOIN instead of GROUP BY + HAVING , which will automatically unselect Users with no Post . 由于在您的用例中,要选择的Posts限制为1,如@Yoshi所述,您可以使用INNER JOIN代替GROUP BY + HAVING ,这将自动取消选择没有Post Users

Instead of what is above, use this: 代替上面的内容,使用以下命令:

$qb = $this->createQueryBuilder('users')
    ->innerJoin('user.posts', 'posts');

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

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