Search code examples
symfonydoctrine-ormdoctrinerelationship

Symfony 5+ Timestamp a ManyToMany relationship


I have a relationship between two entities:

  • FosterFamily
  • Animal

On Animal entity I have a field called "FosterFamiliesHistory" which is a ManyToMany relationship to FosterFamily entity reversed by the "AnimalsHistory" field.

The join table is created and managed automatically by doctrine under the custom name i choosed "foster_family_animal_history".

For some reason I'd like to add a custom property to this join table called "createdAt" to keep a track of the date where the relation has been created.

I know I could totally make a custom collection with an explicit intermediate entity where I could have a total control, but it is a bit overkill for my needs, but if there's no alternatives, I'll do it of course.


Solution

  • According to https://symfonycasts.com/screencast/doctrine-relations/complex-many-to-many, you can't achieve what you asked, without indeed making an explicit intermediate entity ...

    The ManyToMany relationship is unique in Doctrine because Doctrine actually creates & manages a table - the join table - for us. This is the only time in Doctrine where we have a table without a corresponding entity class.

    But what if we needed to add more columns to this table? Like a tagged_at DateTime column? Excellent question! And the answer is... that's not possible! I'm serious! But, it's by design. As soon as you need even one extra column on this join table, you need to stop using a ManyToMany relationship. Instead, you need to create an entity for the join table and manually relate that entity to Question and Tag.