Associations with Doctrine 2

I am trying to create an entity with a doctrine that has three associations with other objects.

So, the element is associated with:

  • Must be associated with One Rssfeed, which it comes from
  • May be associated with one or more locations
  • May be associated with one or more tags

Here is my attempt:

class Item{ /** * @ManyToOne(targetEntity="Rssfeed") */ protected $rssfeed; /** * * @ManyToMany(targetEntity="Location") */ protected $locations; /** * * @ManyToMany(targetEntity="Tag") */ protected $tags; } 

Now

  • If Rssfeed is removed, related items must also be deleted.
  • If an item is deleted, Rssfeeds and locations and tags attached to this item must be detached
  • If the location or tag is removed, the related items should simply be detached, as they are optional associations.

How do I change my code to execute this?

+4
source share
2 answers

For each association in the Item object, add onDelete = "SET NULL" to the @JoinColumn annotation. Inside your location and tag objects, find JoinColumn annotations and add onDelete = "SET NULL" to link to "Item". Under the RssFeed object, find each @JoinColumn annotation and add onDelete = "SET NULL". Please note that you can also use Doctrine cascading operations to achieve this goal (ie Cascade = {"remove"}, etc., however, it will probably be much slower because the work is not performed at the RDBMS level.

+1
source

U need to add @JoinColumn with onDelete = "CASCADE" for $ rssfeed and onDelete = "SET NULL" for foreign keys in Location and Tag objects.

  /** * @ManyToOne(targetEntity="Rssfeed") * @JoinColumn(name="rssfeed_id", referencedColumnName="id", onDelete="CASCADE") */ protected $rssfeed; 
+1
source

All Articles