mennanov
mennanov

Reputation: 1245

Fetching related objects

In Symfony 2 book there is an example of how to do that for ONE $product: http://symfony.com/doc/2.0/book/doctrine.html#fetching-related-objects

It is quite simple:

public function showAction($id)
{
$product = $this->getDoctrine()
    ->getRepository('AcmeStoreBundle:Product')
    ->find($id);

$categoryName = $product->getCategory()->getName();

// ...
}

But what if i want to fetch ALL products with category info joined automatically to each project?

Thank you!

Upvotes: 0

Views: 3045

Answers (2)

Cerad
Cerad

Reputation: 48893

This will do the trick:

$products = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product')->findAll();

However, each time you do a getCategory on a product a sql query will be triggered which could result in performance issues.

What you really want to do is to make yourself a ProductManager service and write an explicit query joining product and category. So only one sql query will be generated. The Doctrine 2 manual has plenty of examples.

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/query-builder.html

Upvotes: 1

Louis-Philippe Huberdeau
Louis-Philippe Huberdeau

Reputation: 5431

You can either iterate over the products and get the categories from there. Adjusting the fetch mode on the relations might help in reducing the amount of queries performed.

However, you might also just write a custom DQL query to get what you need. It might look like something like this:

SELECT p, c
FROM AcmeStoreBundle:Product p
INNER JOIN p.category c

Upvotes: 0

Related Questions