Creating a one to many polymorphic relationship with doctrine

前端 未结 5 2339
猫巷女王i
猫巷女王i 2021-02-18 23:37

Let me start by outlining the scenario. I have a Note object that can be assigned to many different objects

  • A Book can have one or moreNot
5条回答
  •  名媛妹妹
    2021-02-19 00:08

    As you cant have several foreign keys on one column, you have 2 solutuons:

    1. either make one sided one2many relations between Book/Image/Address and Note, so it would create a join table for each relation like book_note, image_note etc. holding the id pairs book.id-note.id etc. (I mean one2many instead of many2many because there usually is no point for a note to know which book or image or address it belongs to)

    http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-unidirectional-with-join-table

    1. or make multiple entities BookNote,ImageNote,AddressNote related to a book/image/address and a note and other data if for example one type of a note has some other data in it.

    2. you can use single table inheritance as described in accepted answer to this question, but it is a solution similar to one proposed by Steven, which makes you hold additional data in the discriminator column.

    Multiple JoinColumns in Symfony2 using Doctrine annotations?

    Doctrine documentation also mentions a performance hit in certain situations.

    http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#performance-impact

    Solution given by Steve Chambers solves a problem but you force the note table to hold unnecessary data(empty id columns for other objects)

提交回复
热议问题