@@ -171,6 +171,32 @@ the ``Product`` entity (and getter & setter methods):
171171 }
172172 }
173173
174+ .. code-block :: php-attributes
175+
176+ // src/Entity/Product.php
177+ namespace App\Entity;
178+
179+ // ...
180+ class Product
181+ {
182+ // ...
183+
184+ #[ORM\ManyToOne(targetEntity: Category::class, inversedBy: "products")]
185+ private $category;
186+
187+ public function getCategory(): ?Category
188+ {
189+ return $this->category;
190+ }
191+
192+ public function setCategory(?Category $category): self
193+ {
194+ $this->category = $category;
195+
196+ return $this;
197+ }
198+ }
199+
174200 .. code-block :: yaml
175201
176202 # src/Resources/config/doctrine/Product.orm.yml
@@ -248,6 +274,38 @@ class that will hold these objects:
248274 // addProduct() and removeProduct() were also added
249275 }
250276
277+ .. code-block :: php-attributes
278+
279+ // src/Entity/Category.php
280+ namespace App\Entity;
281+
282+ // ...
283+ use Doctrine\Common\Collections\ArrayCollection;
284+ use Doctrine\Common\Collections\Collection;
285+
286+ class Category
287+ {
288+ // ...
289+
290+ #[ORM\OneToMany(targetEntity: Product::class, mappedBy: "category")]
291+ private $products;
292+
293+ public function __construct()
294+ {
295+ $this->products = new ArrayCollection();
296+ }
297+
298+ /**
299+ * @return Collection|Product[]
300+ */
301+ public function getProducts(): Collection
302+ {
303+ return $this->products;
304+ }
305+
306+ // addProduct() and removeProduct() were also added
307+ }
308+
251309 .. code-block :: yaml
252310
253311 # src/Resources/config/doctrine/Category.orm.yml
@@ -589,16 +647,30 @@ on that ``Product`` will be set to ``null`` in the database.
589647
590648But, instead of setting the ``category_id `` to null, what if you want the ``Product ``
591649to be *deleted * if it becomes "orphaned" (i.e. without a ``Category ``)? To choose
592- that behavior, use the `orphanRemoval `_ option inside ``Category ``::
650+ that behavior, use the `orphanRemoval `_ option inside ``Category ``:
593651
594- // src/Entity/Category.php
652+ .. configuration-block ::
595653
596- // ...
654+ .. code-block :: php-annotations
655+
656+ // src/Entity/Category.php
657+
658+ // ...
659+
660+ /**
661+ * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category", orphanRemoval=true)
662+ */
663+ private $products;
664+
665+ .. code-block :: php-attributes
666+
667+ // src/Entity/Category.php
668+
669+ // ...
670+
671+ #[ORM\OneToMany(targetEntity: Product::class, mappedBy: "category", orphanRemoval=true)]
672+ private $products;
597673
598- /**
599- * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category", orphanRemoval=true)
600- */
601- private $products;
602674
603675 Thanks to this, if the ``Product `` is removed from the ``Category ``, it will be
604676removed from the database entirely.
0 commit comments