简体   繁体   中英

How can i select extra fields and map them to entity via doctrine query builder in symfony?

I have two entities: Category and Product. Category entity has not link to Product (protected $products // ArrayColection) . I need to calculate total amount of product prices inside each category, and i need to do it ONLY IN SINGLE request via query builder.

Can i do something like this:

$categories = $categoryRepository->createQueryBuilder('c')->join('AppBundle:Product', 'p')->addSelect('SUM(p.price) as c.totalPrice')->addGroupBy('c.id')->getQuery()->getResults();

And then map attribute totalPrice to entity, to have access to it somehow like this:

$categories->get(0)->totalAmount

I CAN'T build extra query, and i CAN'T add relationsip field to Category ($products) to calculte totalSum in entity method by adding price of each product. I should done it only with single query...

What you are talking about is possible with Doctrine > 2.4

Check out their docs for more details on joins: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html

Meanwhile - this is what should work for you:

$query = $this->createQueryBuilder('c')
            ->leftJoin('AppBundle:Product', 'p', 'WITH', 'p.category = c.id')
            ->select('SUM(p.price) as totalPrice')
            ->groupBy('c.id');

Note how we use the leftJoin method parameters - this is what allows you to run the query despite there is no relation between tables.

Hope that works for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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