21.10.2015 Views

1-33

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Symfony2 – Franz Jordán 2011<br />

}<br />

// ...<br />

In this example, you first query for a Product object based on the product's id. This issues a<br />

query for jus the product data and hydrates the $product object with that data. Later, when you<br />

call$product->getCategory()->getName(), Doctrine silently makes a second query to find<br />

the Categorythat's related to this Product. It prepares the $category object and returns it to<br />

you.<br />

What's important is the fact that you have easy access to the product's related category, but the<br />

category data isn't actually retrieved until you ask for the category (i.e. it's "lazily loaded").<br />

You can also query in the other direction:<br />

public function showProductAction($id)<br />

{<br />

$category = $this->getDoctrine()<br />

->getRepository('AcmeStoreBundle:Category')<br />

->find($id);<br />

$products = $category->getProducts();<br />

}<br />

// ...<br />

In this case, the same things occurs: you first query out for a single Category object, and then<br />

Doctrine makes a second query to retrieve the related Product objects, but only once/if you ask<br />

for them (i.e. when you call ->getProducts()). The $products variable is an array of<br />

all Product objects that relate to the given Category object via their category_id value.<br />

97

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!