简体   繁体   English

如何使用Doctrine2对相关的表记录进行计数

[英]How to count related table records using Doctrine2

I'm quite new to doctrine, And i want to carry out a certain task. 我对该学说还很陌生,并且我想执行某些任务。

I have jobs table with category_id column, And obviously categories table. 我有具有category_id列的jobs表,并且显然是categories表。

In Symfony2, I have this repository 在Symfony2中,我有此存储库

<?php

namespace Ibw\JobeetBundle\Repository;

use Doctrine\ORM\EntityRepository;

class CategoryRepository extends EntityRepository
{
    public function getWithAllJobs()
    {
        $qb = $this->createQueryBuilder('c')
                    ->select('c, j')
                    ->leftJoin('c.jobs', 'j');
        return $qb->getQuery()->getResult();
    }

}

Now when i get the result of getWithAllJobs function, It returns all categories even if it have no jobs related. 现在,当我得到getWithAllJobs函数的结果时,即使没有相关的工作,它也会返回所有类别。

I want to only return the categories with related jobs. 我只想返回相关工作的类别。 I'm thinking of counting c.jobs and select categories with c.jobs more than 0 or something. 我正在考虑计算c.jobs并选择c.jobs大于0或类似的类别。 How to do that in doctrine ? 在学说上该怎么做?

And if there's a better way, What is it ? 如果有更好的方法,那是什么?

The only right way to do what you want is using inner join instead of left join . 执行所需操作的唯一正确方法是使用inner join而不是left join Your code should look like this: 您的代码应如下所示:

    $qb = $this->createQueryBuilder('c')
                ->select('c, j')
                ->innerJoin('c.jobs', 'j');

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

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