Search code examples
zend-frameworkdoctrine-ormzend-framework2

Finding out if an entity has relations - How to?


I'm trying to find out a way to find the relations of a specific entity, say one targeted for deletion.

Example setup:

  • Country entity can have many Currencies.
  • Currency entity can have Countries.
  • A Country may have a primary Currency.

Therefore, the setup is: Country <-> (1-n) <-> CountryCurrency <-> (n-1) <-> Currency.

In the above example it's easy to find if a Country, targeted for deletion, has any associated Currencies.

However, imagine that the above is setup in a global kind of way and usable for other modules within the application.

If another module, Address for example, used a Country in a uni-directional relationship (an Address has one Country): how can I figure out that the specific Country entity may not be deleted without trying to and thus receiving a Foreign Key constraint error?

I'm hoping that Doctrine has something for this built in, but haven't been able to find it in the documentation. Have been Google'ing it for a while now as well without success. Always in the trend of: "well, you just $entity->getSomeRelation()->count() > 0 and you know", but I'm looking for a generic solution/method that can apply to any entity.


Solution

  • There is no generic solution for it because it always depends on your business model.

    Deleting entity with relation can lead to different scenarios:

    • deleting related entities as well
    • setting the relation to null
    • or disallow deleting at all.

    So it's up to you to do the check mannualy, depending on your case.