原则查询一个实体在其他表上出现多少次

时间:2019-04-05 14:56:01

标签: php symfony doctrine

假设我有两个表:

Customer
id | name
1  | John
2  | Chris

Sales
id | client_id | price
1  | 1         | 100
2  | 1         | 200
3  | 1         | 300
4  | 2         | 150
5  | 2         | 250

表之间的关系是1:M

如果我想返回下面的数据,我的查询应该是什么样?

client_name | number of sales
John        | 3
Chris       | 2

现在我的querybuilder看起来像这样,只需简单的选择*

$objs = $this->getDoctrine()->getManager()
                    ->getRepository(Customer::class)
                    ->createQueryBuilder('obj');

            $objs = $objs->getQuery()->getResult();

我应该使用某种联接还是子查询?希望得到一些指导,谢谢。

3 个答案:

答案 0 :(得分:2)

@Arno Hilke的基本写法,但进行了一些更改(并假设您的<div id="fixed"> </div> <div id="content"> </div> #fixed { height: 50px; width: 100%; background-color: green; position: fixed; } #content { height: 2000px; background: grey; margin-top: 50px; } 实体实际上被命名为Customer):

Client

答案 1 :(得分:1)

加入您的销售表。按客户分组并计算每个客户的出现次数。像这样的东西应该可以工作,具体取决于您的确切实体定义:

$query = $this->getDoctrine()->getManager()
           ->getRepository(Customer::class)
           ->createQueryBuilder('customer')
           ->select('customer.id as id, count(customer.id) as number');
           ->join('customer.sales', 'sales')
           ->groupBy('sales');


$result = $query->getQuery()->getArrayResult();

答案 2 :(得分:0)

Thank you @Arno Hilke and @Michał Tomczuk.

I changed the code a little to fit my needs. I needed some conditions in the select, so instead of COUNT I used SUM, the code ended like this:

$query = $this->getDoctrine()->getManager()
              ->getRepository(Customer::class)
              ->createQueryBuilder('c')
              ->select("c.name, SUM(CASE WHEN s.conditioneOne = 'valueOne' AND s.conditionTwo = 'valueTwo' THEN 1 ELSE 0 END) AS number_of_sales")
                    ->join('c.sales', 's')
                    ->groupBy('s.costumer')
                    ->orderBy('number_of_sales', 'DESC');

$results = $query->getQuery()->getArrayResult();