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

Finally, now that you've added a new property to both the Category and Product classes, tell<br />

Doctrine to generate the missing getter and setter methods for you:<br />

php app/console doctrine:generate:entities Acme<br />

Ignore the Doctrine metadata for a moment. You now have two classes -<br />

Category and Product with a natural one-to-many relationship. The Category class holds an<br />

array of Product objects and theProduct object can hold one Category object. In other words -<br />

you've built your classes in a way that makes sense for your needs. The fact that the data needs<br />

to be persisted to a database is always secondary.<br />

Now, look at the metadata above the $category property on the Product class. The information<br />

here tells doctrine that the related class is Category and that it should store the id of the<br />

category record on a category_id field that lives on the product table. In other words, the<br />

related Category object will be stored on the $category property, but behind the scenes,<br />

Doctrine will persist this relationship by storing the category's id value on a category_id column<br />

of the product table.<br />

The metadata above the $products property of the Category object is less important, and<br />

simply tells Doctrine to look at the Product.category property to figure out how the<br />

relationship is mapped.<br />

Before you continue, be sure to tell Doctrine to add the new category table,<br />

andproduct.category_id column, and new foreign key:<br />

php app/console doctrine:schema:update --force<br />

95

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

Saved successfully!

Ooh no, something went wrong!