0

I'm a big begginer in Symfony, coming from Ruby on Rails world and trying to get same behaviours.

I have a simple application with 2 entities : Product and Category, with the relation Product belongs to Category and Category has many Products.

class Category {
  [ ... ]
  /** 
   * @ORM\OneToMany(targetEntity="Product", mappedBy="category", cascade={"all"}) 
   */
  protected $products;
}
class Product {
  [ ... ]
  /** 
   * @ORM\ManyToOne(targetEntity="Category", inversedBy="products", cascade={"all"}) 
   */
  protected $category;
}

What I'm trying to do is to delete every nested products when I'm deleting a Category.

My current action looks like

public function deleteAction($id, Request $request)
{
    $repository = $this->getDoctrine()->getRepository('AppBundle:Category');
    $category = $repository->find($id);
    $em = $this->getDoctrine()->getManager();
    $em->remove($category);
    $em->flush();
    return $this->redirect('/categories/');
}

A simple method could be remove all the products in the controller, but it's not very maintainable and not very object oriented. I'm looking about a practice to remove all the products of the deleted category directly in the model. A method, in RoR, is the callbacks (named after_destroy), automatically called when the object is destroyed. Is there any looking-like method in Symfony ?

pierallard
  • 3,326
  • 3
  • 21
  • 48
  • Have you considered using `cascade={"remove"}`? Related SO q/a: http://stackoverflow.com/questions/24612664/understanding-doctrine-cascade-operations – Jovan Perovic Jul 07 '15 at 14:15
  • Check event listeners and subscribers http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html – Vadim Ashikhman Jul 07 '15 at 14:23
  • 2
    I suggest you to use the `onDelete` annotation like `onDelete="CASCADE"` – Matteo Jul 07 '15 at 14:36

0 Answers0