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 />

This task should only be really used during development. For a more robust method of<br />

systematically updating your production database, read about Doctrine migrations.<br />

Saving Related Entities<br />

Now, let's see the code in action. Imagine you're inside a controller:<br />

// ...<br />

use Acme\StoreBundle\Entity\Category;<br />

use Acme\StoreBundle\Entity\Product;<br />

use Symfony\Component\HttpFoundation\Response;<br />

// ...<br />

class DefaultController extends Controller<br />

{<br />

public function createProductAction()<br />

{<br />

$category = new Category();<br />

$category->setName('Main Products');<br />

$product = new Product();<br />

$product->setName('Foo');<br />

$product->setPrice(19.99);<br />

// relate this product to the category<br />

$product->setCategory($category);<br />

$em = $this->getDoctrine()->getEntityManager();<br />

$em->persist($category);<br />

$em->persist($product);<br />

$em->flush();<br />

}<br />

}<br />

return new Response(<br />

);<br />

'Created product id: '.$product->getId().' and category id: '.$category->getId()<br />

Now, a single row is added to both the category and product tables.<br />

The product.category_idcolumn for the new product is set to whatever the id is of the new<br />

category. Doctrine manages the persistence of this relationship for you.<br />

Fetching Related Objects<br />

When you need to fetch associated objects, your workflow looks just like it did before. First,<br />

fetch a$product object and then access its related Category:<br />

public function showAction($id)<br />

{<br />

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

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

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

$categoryName = $product->getCategory()->getName();<br />

96

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

Saved successfully!

Ooh no, something went wrong!