@@ -171,6 +171,32 @@ the ``Product`` entity (and getter & setter methods):
171
171
}
172
172
}
173
173
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
+
174
200
.. code-block :: yaml
175
201
176
202
# src/Resources/config/doctrine/Product.orm.yml
@@ -248,6 +274,38 @@ class that will hold these objects:
248
274
// addProduct() and removeProduct() were also added
249
275
}
250
276
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
+
251
309
.. code-block :: yaml
252
310
253
311
# src/Resources/config/doctrine/Category.orm.yml
@@ -597,16 +655,30 @@ on that ``Product`` will be set to ``null`` in the database.
597
655
598
656
But, instead of setting the ``category_id `` to null, what if you want the ``Product ``
599
657
to be *deleted * if it becomes "orphaned" (i.e. without a ``Category ``)? To choose
600
- that behavior, use the `orphanRemoval `_ option inside ``Category ``::
658
+ that behavior, use the `orphanRemoval `_ option inside ``Category ``:
601
659
602
- // src/Entity/Category.php
660
+ .. configuration-block ::
603
661
604
- // ...
662
+ .. code-block :: php-annotations
663
+
664
+ // src/Entity/Category.php
665
+
666
+ // ...
667
+
668
+ /**
669
+ * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category", orphanRemoval=true)
670
+ */
671
+ private $products;
672
+
673
+ .. code-block :: php-attributes
674
+
675
+ // src/Entity/Category.php
676
+
677
+ // ...
678
+
679
+ #[ORM\OneToMany(targetEntity: Product::class, mappedBy: "category", orphanRemoval=true)]
680
+ private $products;
605
681
606
- /**
607
- * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category", orphanRemoval=true)
608
- */
609
- private $products;
610
682
611
683
Thanks to this, if the ``Product `` is removed from the ``Category ``, it will be
612
684
removed from the database entirely.
0 commit comments