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 />
php app/console doctrine:generate:entity --entity="AcmeStoreBundle:Category" --<br />
fields="name:string(255)"<br />
This task generates the Category entity for you, with an id field, a name field and the<br />
associated getter and setter functions.<br />
Relationship Mapping Metadata<br />
To relate the Category and Product entities, start by creating a products property on<br />
the Categoryclass:<br />
// src/Acme/StoreBundle/Entity/Category.php<br />
// ...<br />
use Doctrine\Common\Collections\ArrayCollection;<br />
class Category<br />
{<br />
// ...<br />
/**<br />
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")<br />
*/<br />
protected $products;<br />
}<br />
public function __construct()<br />
{<br />
}<br />
$this->products = new ArrayCollection();<br />
First, since a Category object will relate to many Product objects, a products array property is<br />
added to hold those Product objects. Again, this isn't done because Doctrine needs it, but<br />
instead because it makes sense in the application for each Category to hold an array<br />
of Product objects.<br />
The code in the __construct() method is important because Doctrine requires<br />
the$products property to be an ArrayCollection object. This object looks and acts<br />
almost exactly like an array, but has some added flexibility. If this makes you uncomfortable,<br />
don't worry. Just imagine that it's an array and you'll be in good shape.<br />
Next, since each Product class can relate to exactly one Category object, you'll want to add<br />
a$category property to the Product class:<br />
// src/Acme/StoreBundle/Entity/Product.php<br />
// ...<br />
class Product<br />
{<br />
// ...<br />
}<br />
/**<br />
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")<br />
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")<br />
*/<br />
protected $category;<br />
94