override-field-association-mappings-in-subclasses.rst 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. Override Field Association Mappings In Subclasses
  2. -------------------------------------------------
  3. Sometimes there is a need to persist entities but override all or part of the
  4. mapping metadata. Sometimes also the mapping to override comes from entities
  5. using traits where the traits have mapping metadata.
  6. This tutorial explains how to override mapping metadata,
  7. i.e. attributes and associations metadata in particular. The example here shows
  8. the overriding of a class that uses a trait but is similar when extending a base
  9. class as shown at the end of this tutorial.
  10. Suppose we have a class ExampleEntityWithOverride. This class uses trait ExampleTrait:
  11. .. code-block:: php
  12. <?php
  13. /**
  14. * @Entity
  15. *
  16. * @AttributeOverrides({
  17. * @AttributeOverride(name="foo",
  18. * column=@Column(
  19. * name = "foo_overridden",
  20. * type = "integer",
  21. * length = 140,
  22. * nullable = false,
  23. * unique = false
  24. * )
  25. * )
  26. * })
  27. *
  28. * @AssociationOverrides({
  29. * @AssociationOverride(name="bar",
  30. * joinColumns=@JoinColumn(
  31. * name="example_entity_overridden_bar_id", referencedColumnName="id"
  32. * )
  33. * )
  34. * })
  35. */
  36. class ExampleEntityWithOverride
  37. {
  38. use ExampleTrait;
  39. }
  40. /**
  41. * @Entity
  42. */
  43. class Bar
  44. {
  45. /** @Id @Column(type="string") */
  46. private $id;
  47. }
  48. The docblock is showing metadata override of the attribute and association type. It
  49. basically changes the names of the columns mapped for a property ``foo`` and for
  50. the association ``bar`` which relates to Bar class shown above. Here is the trait
  51. which has mapping metadata that is overridden by the annotation above:
  52. .. code-block:: php
  53. /**
  54. * Trait class
  55. */
  56. trait ExampleTrait
  57. {
  58. /** @Id @Column(type="string") */
  59. private $id;
  60. /**
  61. * @Column(name="trait_foo", type="integer", length=100, nullable=true, unique=true)
  62. */
  63. protected $foo;
  64. /**
  65. * @OneToOne(targetEntity="Bar", cascade={"persist", "merge"})
  66. * @JoinColumn(name="example_trait_bar_id", referencedColumnName="id")
  67. */
  68. protected $bar;
  69. }
  70. The case for just extending a class would be just the same but:
  71. .. code-block:: php
  72. class ExampleEntityWithOverride extends BaseEntityWithSomeMapping
  73. {
  74. // ...
  75. }
  76. Overriding is also supported via XML and YAML.