How to get an entity and a count in the same query?

时间:2018-10-02 09:17:14

标签: php symfony doctrine-orm

I've created the following repository and method. The method does what you would expect it to do except for one thing. It cannot return both ->select('ol') and ->select('count(ol.product) as totalProducts'). As soon as I inclode the ->select('ol') it will ignore the count.

class OrderLineRepository
{
    // ...

    public function getOpenOrders()
    {
        $qb = $this->createQueryBuilder('ol');
        $orders = $qb
                ->select('count(ol.product) as totalProducts')
                ->select('ol')
                ->where('BIT_AND(ol.flags, 3) = 2')
                ->groupBy('ol.orderId')
                ->setMaxResults(100)
                ->getQuery()
                ->getResult()
            ;

            return $orders;
    }

    // ...
}

I am still in the early stages of mastering symfony and this could possibly quite a stupid question. But it's still a question I'm currently facing. Can someone help me out?

Update

Witht the help of RiggsFolly I now get the following result by using ->addSelect(...) instead of ->select(...).

array:10 [
    // ...
    array:2 [
        0 => OrderLine {
            id: 8068005
            product: Product {#1503 ▶}
            supplier: Supplier {#1552 ▶}
            reference: Reference {#1528 ▶}
        }
        "products" => "3"
    ]
    // ...
]

Ideally, I would like to get it like this:

array:10 [
    // ...
    array:2 [
        id: 8068005
        product: Product {#1503 ▶}
        supplier: Supplier {#1552 ▶}
        reference: Reference {#1528 ▶}
        "products" => "3"
    ]
    // ...
]

1 个答案:

答案 0 :(得分:2)

我不知道它与OrderLine和Products有什么关系;但也许您可以在它们之间创建数据库关系,这样您将获得与OrderLine相关的一系列产品。

最后,获取产品数量:

$productsNumber = count($orderLine->getProducts());  

更新

在这种情况下,产品总数将与订单行总数相同,对吗?

因此,我认为总产品不是 Order 属性;并且它不应该是OrderLine对象的一部分,相反,您可能可以算出由Doctrine检索到的OrderLines对象,它将成为您的totalProduct。

再往前看,您还可以创建一个与您的Order对象(一对多)相关的OrderLine实体。然后,您可以使用Doctrine查询您的Order实体,并计算OrderLines实体的Order属性,该属性将与总产品相同。