composite-primary-keys.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. Composite and Foreign Keys as Primary Key
  2. =========================================
  3. .. versionadded:: 2.1
  4. Doctrine 2 supports composite primary keys natively. Composite keys are a very powerful relational database concept
  5. and we took good care to make sure Doctrine 2 supports as many of the composite primary key use-cases.
  6. For Doctrine 2.0 composite keys of primitive data-types are supported, for Doctrine 2.1 even foreign keys as
  7. primary keys are supported.
  8. This tutorial shows how the semantics of composite primary keys work and how they map to the database.
  9. General Considerations
  10. ~~~~~~~~~~~~~~~~~~~~~~
  11. Every entity with a composite key cannot use an id generator other than "ASSIGNED". That means
  12. the ID fields have to have their values set before you call ``EntityManager#persist($entity)``.
  13. Primitive Types only
  14. ~~~~~~~~~~~~~~~~~~~~
  15. Even in version 2.0 you can have composite keys as long as they only consist of the primitive types
  16. ``integer`` and ``string``. Suppose you want to create a database of cars and use the model-name
  17. and year of production as primary keys:
  18. .. configuration-block::
  19. .. code-block:: php
  20. <?php
  21. namespace VehicleCatalogue\Model;
  22. /**
  23. * @Entity
  24. */
  25. class Car
  26. {
  27. /** @Id @Column(type="string") */
  28. private $name;
  29. /** @Id @Column(type="integer") */
  30. private $year
  31. public function __construct($name, $year)
  32. {
  33. $this->name = $name;
  34. $this->year = $year;
  35. }
  36. public function getModelName()
  37. {
  38. return $this->name;
  39. }
  40. public function getYearOfProduction()
  41. {
  42. return $this->year;
  43. }
  44. }
  45. .. code-block:: xml
  46. <?xml version="1.0" encoding="UTF-8"?>
  47. <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
  48. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  49. xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
  50. http://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  51. <entity name="VehicleCatalogue\Model\Car">
  52. <id field="name" type="string" />
  53. <id field="year" type="integer" />
  54. </entity>
  55. </doctrine-mapping>
  56. .. code-block:: yaml
  57. VehicleCatalogue\Model\Car:
  58. type: entity
  59. id:
  60. name:
  61. type: string
  62. year:
  63. type: integer
  64. Now you can use this entity:
  65. .. code-block:: php
  66. <?php
  67. namespace VehicleCatalogue\Model;
  68. // $em is the EntityManager
  69. $car = new Car("Audi A8", 2010);
  70. $em->persist($car);
  71. $em->flush();
  72. And for querying you can use arrays to both DQL and EntityRepositories:
  73. .. code-block:: php
  74. <?php
  75. namespace VehicleCatalogue\Model;
  76. // $em is the EntityManager
  77. $audi = $em->find("VehicleCatalogue\Model\Car", array("name" => "Audi A8", "year" => 2010));
  78. $dql = "SELECT c FROM VehicleCatalogue\Model\Car c WHERE c.id = ?1";
  79. $audi = $em->createQuery($dql)
  80. ->setParameter(1, array("name" => "Audi A8", "year" => 2010))
  81. ->getSingleResult();
  82. You can also use this entity in associations. Doctrine will then generate two foreign keys one for ``name``
  83. and to ``year`` to the related entities.
  84. .. note::
  85. This example shows how you can nicely solve the requirement for existing
  86. values before ``EntityManager#persist()``: By adding them as mandatory values for the constructor.
  87. Identity through foreign Entities
  88. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  89. .. note::
  90. Identity through foreign entities is only supported with Doctrine 2.1
  91. There are tons of use-cases where the identity of an Entity should be determined by the entity
  92. of one or many parent entities.
  93. - Dynamic Attributes of an Entity (for example Article). Each Article has many
  94. attributes with primary key "article_id" and "attribute_name".
  95. - Address object of a Person, the primary key of the address is "user_id". This is not a case of a composite primary
  96. key, but the identity is derived through a foreign entity and a foreign key.
  97. - Join Tables with metadata can be modelled as Entity, for example connections between two articles
  98. with a little description and a score.
  99. The semantics of mapping identity through foreign entities are easy:
  100. - Only allowed on Many-To-One or One-To-One associations.
  101. - Plug an ``@Id`` annotation onto every association.
  102. - Set an attribute ``association-key`` with the field name of the association in XML.
  103. - Set a key ``associationKey:`` with the field name of the association in YAML.
  104. Use-Case 1: Dynamic Attributes
  105. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  106. We keep up the example of an Article with arbitrary attributes, the mapping looks like this:
  107. .. configuration-block::
  108. .. code-block:: php
  109. <?php
  110. namespace Application\Model;
  111. use Doctrine\Common\Collections\ArrayCollection;
  112. /**
  113. * @Entity
  114. */
  115. class Article
  116. {
  117. /** @Id @Column(type="integer") @GeneratedValue */
  118. private $id;
  119. /** @Column(type="string") */
  120. private $title;
  121. /**
  122. * @OneToMany(targetEntity="ArticleAttribute", mappedBy="article", cascade={"ALL"}, indexBy="attribute")
  123. */
  124. private $attributes;
  125. public function addAttribute($name, $value)
  126. {
  127. $this->attributes[$name] = new ArticleAttribute($name, $value, $this);
  128. }
  129. }
  130. /**
  131. * @Entity
  132. */
  133. class ArticleAttribute
  134. {
  135. /** @Id @ManyToOne(targetEntity="Article", inversedBy="attributes") */
  136. private $article;
  137. /** @Id @Column(type="string") */
  138. private $attribute;
  139. /** @Column(type="string") */
  140. private $value;
  141. public function __construct($name, $value, $article)
  142. {
  143. $this->attribute = $name;
  144. $this->value = $value;
  145. $this->article = $article;
  146. }
  147. }
  148. .. code-block:: xml
  149. <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping"
  150. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  151. xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
  152. http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  153. <entity name="Application\Model\ArticleAttribute">
  154. <id name="article" association-key="true" />
  155. <id name="attribute" type="string" />
  156. <field name="value" type="string" />
  157. <many-to-one field="article" target-entity="Article" inversed-by="attributes" />
  158. <entity>
  159. </doctrine-mapping>
  160. .. code-block:: yaml
  161. Application\Model\ArticleAttribute:
  162. type: entity
  163. id:
  164. article:
  165. associationKey: true
  166. attribute:
  167. type: string
  168. fields:
  169. value:
  170. type: string
  171. manyToOne:
  172. article:
  173. targetEntity: Article
  174. inversedBy: attributes
  175. Use-Case 2: Simple Derived Identity
  176. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  177. Sometimes you have the requirement that two objects are related by a One-To-One association
  178. and that the dependent class should re-use the primary key of the class it depends on.
  179. One good example for this is a user-address relationship:
  180. .. configuration-block::
  181. .. code-block:: php
  182. <?php
  183. /**
  184. * @Entity
  185. */
  186. class User
  187. {
  188. /** @Id @Column(type="integer") @GeneratedValue */
  189. private $id;
  190. }
  191. /**
  192. * @Entity
  193. */
  194. class Address
  195. {
  196. /** @Id @OneToOne(targetEntity="User") */
  197. private $user;
  198. }
  199. .. code-block:: yaml
  200. User:
  201. type: entity
  202. id:
  203. id:
  204. type: integer
  205. generator:
  206. strategy: AUTO
  207. Address:
  208. type: entity
  209. id:
  210. user:
  211. associationKey: true
  212. oneToOne:
  213. user:
  214. targetEntity: User
  215. Use-Case 3: Join-Table with Metadata
  216. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  217. In the classic order product shop example there is the concept of the order item
  218. which contains references to order and product and additional data such as the amount
  219. of products purchased and maybe even the current price.
  220. .. code-block:: php
  221. <?php
  222. use Doctrine\Common\Collections\ArrayCollection;
  223. /** @Entity */
  224. class Order
  225. {
  226. /** @Id @Column(type="integer") @GeneratedValue */
  227. private $id;
  228. /** @ManyToOne(targetEntity="Customer") */
  229. private $customer;
  230. /** @OneToMany(targetEntity="OrderItem", mappedBy="order") */
  231. private $items;
  232. /** @Column(type="boolean") */
  233. private $payed = false;
  234. /** @Column(type="boolean") */
  235. private $shipped = false;
  236. /** @Column(type="datetime") */
  237. private $created;
  238. public function __construct(Customer $customer)
  239. {
  240. $this->customer = $customer;
  241. $this->items = new ArrayCollection();
  242. $this->created = new \DateTime("now");
  243. }
  244. }
  245. /** @Entity */
  246. class Product
  247. {
  248. /** @Id @Column(type="integer") @GeneratedValue */
  249. private $id;
  250. /** @Column(type="string") */
  251. private $name;
  252. /** @Column(type="decimal") */
  253. private $currentPrice;
  254. public function getCurrentPrice()
  255. {
  256. return $this->currentPrice;
  257. }
  258. }
  259. /** @Entity */
  260. class OrderItem
  261. {
  262. /** @Id @ManyToOne(targetEntity="Order") */
  263. private $order;
  264. /** @Id @ManyToOne(targetEntity="Product") */
  265. private $product;
  266. /** @Column(type="integer") */
  267. private $amount = 1;
  268. /** @Column(type="decimal") */
  269. private $offeredPrice;
  270. public function __construct(Order $order, Product $product, $amount = 1)
  271. {
  272. $this->order = $order;
  273. $this->product = $product;
  274. $this->offeredPrice = $product->getCurrentPrice();
  275. }
  276. }
  277. Performance Considerations
  278. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  279. Using composite keys always comes with a performance hit compared to using entities with
  280. a simple surrogate key. This performance impact is mostly due to additional PHP code that is
  281. necessary to handle this kind of keys, most notably when using derived identifiers.
  282. On the SQL side there is not much overhead as no additional or unexpected queries have to be
  283. executed to manage entities with derived foreign keys.