association-mapping.rst 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. Association Mapping
  2. ===================
  3. This chapter introduces association mappings which are used to explain
  4. references between objects and are mapped to a relational database using
  5. foreign keys.
  6. Instead of working with the foreign keys directly you will always work with
  7. references to objects:
  8. - A reference to a single object is represented by a foreign key.
  9. - A collection of objects is represented by many foreign keys pointing to the object holding the collection
  10. This chapter is split into three different sections.
  11. - A list of all the possible association mapping use-cases is given.
  12. - :ref:`association_mapping_defaults` are explained that simplify the use-case examples.
  13. - :ref:`collections` are introduced that contain entities in associations.
  14. To master associations you should also learn about :doc:`owning and inverse sides of associations <unitofwork-associations>`
  15. One-To-One, Unidirectional
  16. --------------------------
  17. A unidirectional one-to-one association is very common. Here is an
  18. example of a ``Product`` that has one ``Shipping`` object
  19. associated to it. The ``Shipping`` side does not reference back to
  20. the ``Product`` so it is unidirectional.
  21. .. configuration-block::
  22. .. code-block:: php
  23. <?php
  24. /** @Entity **/
  25. class Product
  26. {
  27. // ...
  28. /**
  29. * @OneToOne(targetEntity="Shipping")
  30. * @JoinColumn(name="shipping_id", referencedColumnName="id")
  31. **/
  32. private $shipping;
  33. // ...
  34. }
  35. /** @Entity **/
  36. class Shipping
  37. {
  38. // ...
  39. }
  40. .. code-block:: xml
  41. <doctrine-mapping>
  42. <entity class="Product">
  43. <one-to-one field="shipping" target-entity="Shipping">
  44. <join-column name="shipping_id" referenced-column-name="id" />
  45. </one-to-one>
  46. </entity>
  47. </doctrine-mapping>
  48. .. code-block:: yaml
  49. Product:
  50. type: entity
  51. oneToOne:
  52. shipping:
  53. targetEntity: Shipping
  54. joinColumn:
  55. name: shipping_id
  56. referencedColumnName: id
  57. Note that the @JoinColumn is not really necessary in this example,
  58. as the defaults would be the same.
  59. Generated MySQL Schema:
  60. .. code-block:: sql
  61. CREATE TABLE Product (
  62. id INT AUTO_INCREMENT NOT NULL,
  63. shipping_id INT DEFAULT NULL,
  64. UNIQUE INDEX UNIQ_6FBC94267FE4B2B (shipping_id),
  65. PRIMARY KEY(id)
  66. ) ENGINE = InnoDB;
  67. CREATE TABLE Shipping (
  68. id INT AUTO_INCREMENT NOT NULL,
  69. PRIMARY KEY(id)
  70. ) ENGINE = InnoDB;
  71. ALTER TABLE Product ADD FOREIGN KEY (shipping_id) REFERENCES Shipping(id);
  72. One-To-One, Bidirectional
  73. -------------------------
  74. Here is a one-to-one relationship between a ``Customer`` and a
  75. ``Cart``. The ``Cart`` has a reference back to the ``Customer`` so
  76. it is bidirectional.
  77. .. configuration-block::
  78. .. code-block:: php
  79. <?php
  80. /** @Entity **/
  81. class Customer
  82. {
  83. // ...
  84. /**
  85. * @OneToOne(targetEntity="Cart", mappedBy="customer")
  86. **/
  87. private $cart;
  88. // ...
  89. }
  90. /** @Entity **/
  91. class Cart
  92. {
  93. // ...
  94. /**
  95. * @OneToOne(targetEntity="Customer", inversedBy="cart")
  96. * @JoinColumn(name="customer_id", referencedColumnName="id")
  97. **/
  98. private $customer;
  99. // ...
  100. }
  101. .. code-block:: xml
  102. <doctrine-mapping>
  103. <entity name="Customer">
  104. <one-to-one field="cart" target-entity="Cart" mapped-by="customer" />
  105. </entity>
  106. <entity name="Cart">
  107. <one-to-one field="customer" target-entity="Customer" inversed-by="cart">
  108. <join-column name="customer_id" referenced-column-name="id" />
  109. </one-to-one>
  110. </entity>
  111. </doctrine-mapping>
  112. .. code-block:: yaml
  113. Customer:
  114. oneToOne:
  115. cart:
  116. targetEntity: Cart
  117. mappedBy: customer
  118. Cart:
  119. oneToOne:
  120. customer:
  121. targetEntity: Customer
  122. inversedBy: cart
  123. joinColumn:
  124. name: customer_id
  125. referencedColumnName: id
  126. Note that the @JoinColumn is not really necessary in this example,
  127. as the defaults would be the same.
  128. Generated MySQL Schema:
  129. .. code-block:: sql
  130. CREATE TABLE Cart (
  131. id INT AUTO_INCREMENT NOT NULL,
  132. customer_id INT DEFAULT NULL,
  133. PRIMARY KEY(id)
  134. ) ENGINE = InnoDB;
  135. CREATE TABLE Customer (
  136. id INT AUTO_INCREMENT NOT NULL,
  137. PRIMARY KEY(id)
  138. ) ENGINE = InnoDB;
  139. ALTER TABLE Cart ADD FOREIGN KEY (customer_id) REFERENCES Customer(id);
  140. See how the foreign key is defined on the owning side of the
  141. relation, the table ``Cart``.
  142. One-To-One, Self-referencing
  143. ----------------------------
  144. You can easily have self referencing one-to-one relationships like
  145. below.
  146. .. code-block:: php
  147. <?php
  148. /** @Entity **/
  149. class Student
  150. {
  151. // ...
  152. /**
  153. * @OneToOne(targetEntity="Student")
  154. * @JoinColumn(name="mentor_id", referencedColumnName="id")
  155. **/
  156. private $mentor;
  157. // ...
  158. }
  159. Note that the @JoinColumn is not really necessary in this example,
  160. as the defaults would be the same.
  161. With the generated MySQL Schema:
  162. .. code-block:: sql
  163. CREATE TABLE Student (
  164. id INT AUTO_INCREMENT NOT NULL,
  165. mentor_id INT DEFAULT NULL,
  166. PRIMARY KEY(id)
  167. ) ENGINE = InnoDB;
  168. ALTER TABLE Student ADD FOREIGN KEY (mentor_id) REFERENCES Student(id);
  169. One-To-Many, Unidirectional with Join Table
  170. -------------------------------------------
  171. A unidirectional one-to-many association can be mapped through a
  172. join table. From Doctrine's point of view, it is simply mapped as a
  173. unidirectional many-to-many whereby a unique constraint on one of
  174. the join columns enforces the one-to-many cardinality.
  175. .. note::
  176. One-To-Many uni-directional relations with join-table only
  177. work using the @ManyToMany annotation and a unique-constraint.
  178. The following example sets up such a unidirectional one-to-many association:
  179. .. configuration-block::
  180. .. code-block:: php
  181. <?php
  182. /** @Entity **/
  183. class User
  184. {
  185. // ...
  186. /**
  187. * @ManyToMany(targetEntity="Phonenumber")
  188. * @JoinTable(name="users_phonenumbers",
  189. * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
  190. * inverseJoinColumns={@JoinColumn(name="phonenumber_id", referencedColumnName="id", unique=true)}
  191. * )
  192. **/
  193. private $phonenumbers;
  194. public function __construct()
  195. {
  196. $this->phonenumbers = new \Doctrine\Common\Collections\ArrayCollection();
  197. }
  198. // ...
  199. }
  200. /** @Entity **/
  201. class Phonenumber
  202. {
  203. // ...
  204. }
  205. .. code-block:: xml
  206. <doctrine-mapping>
  207. <entity name="User">
  208. <many-to-many field="phonenumbers" target-entity="Phonenumber">
  209. <join-table name="users_phonenumbers">
  210. <join-columns>
  211. <join-column name="user_id" referenced-column-name="id" />
  212. </join-columns>
  213. <inverse-join-columns>
  214. <join-column name="phonenumber_id" referenced-column-name="id" unique="true" />
  215. </inverse-join-columns>
  216. </join-table>
  217. </many-to-many>
  218. </entity>
  219. </doctrine-mapping>
  220. .. code-block:: yaml
  221. User:
  222. type: entity
  223. manyToMany:
  224. phonenumbers:
  225. targetEntity: Phonenumber
  226. joinTable:
  227. name: users_phonenumbers
  228. joinColumns:
  229. user_id:
  230. referencedColumnName: id
  231. inverseJoinColumns:
  232. phonenumber_id:
  233. referencedColumnName: id
  234. unique: true
  235. Generates the following MySQL Schema:
  236. .. code-block:: sql
  237. CREATE TABLE User (
  238. id INT AUTO_INCREMENT NOT NULL,
  239. PRIMARY KEY(id)
  240. ) ENGINE = InnoDB;
  241. CREATE TABLE users_phonenumbers (
  242. user_id INT NOT NULL,
  243. phonenumber_id INT NOT NULL,
  244. UNIQUE INDEX users_phonenumbers_phonenumber_id_uniq (phonenumber_id),
  245. PRIMARY KEY(user_id, phonenumber_id)
  246. ) ENGINE = InnoDB;
  247. CREATE TABLE Phonenumber (
  248. id INT AUTO_INCREMENT NOT NULL,
  249. PRIMARY KEY(id)
  250. ) ENGINE = InnoDB;
  251. ALTER TABLE users_phonenumbers ADD FOREIGN KEY (user_id) REFERENCES User(id);
  252. ALTER TABLE users_phonenumbers ADD FOREIGN KEY (phonenumber_id) REFERENCES Phonenumber(id);
  253. Many-To-One, Unidirectional
  254. ---------------------------
  255. You can easily implement a many-to-one unidirectional association
  256. with the following:
  257. .. configuration-block::
  258. .. code-block:: php
  259. <?php
  260. /** @Entity **/
  261. class User
  262. {
  263. // ...
  264. /**
  265. * @ManyToOne(targetEntity="Address")
  266. * @JoinColumn(name="address_id", referencedColumnName="id")
  267. **/
  268. private $address;
  269. }
  270. /** @Entity **/
  271. class Address
  272. {
  273. // ...
  274. }
  275. .. code-block:: xml
  276. <doctrine-mapping>
  277. <entity name="User">
  278. <many-to-one field="address" target-entity="Address">
  279. <join-column name="address_id" referenced-column-name="id" />
  280. </many-to-one>
  281. </entity>
  282. </doctrine-mapping>
  283. .. code-block:: yaml
  284. User:
  285. type: entity
  286. manyToOne:
  287. address:
  288. targetEntity: Address
  289. joinColumn:
  290. name: address_id
  291. referencedColumnName: id
  292. .. note::
  293. The above ``@JoinColumn`` is optional as it would default
  294. to ``address_id`` and ``id`` anyways. You can omit it and let it
  295. use the defaults.
  296. Generated MySQL Schema:
  297. .. code-block:: sql
  298. CREATE TABLE User (
  299. id INT AUTO_INCREMENT NOT NULL,
  300. address_id INT DEFAULT NULL,
  301. PRIMARY KEY(id)
  302. ) ENGINE = InnoDB;
  303. CREATE TABLE Address (
  304. id INT AUTO_INCREMENT NOT NULL,
  305. PRIMARY KEY(id)
  306. ) ENGINE = InnoDB;
  307. ALTER TABLE User ADD FOREIGN KEY (address_id) REFERENCES Address(id);
  308. One-To-Many, Bidirectional
  309. --------------------------
  310. Bidirectional one-to-many associations are very common. The
  311. following code shows an example with a Product and a Feature
  312. class:
  313. .. configuration-block::
  314. .. code-block:: php
  315. <?php
  316. /** @Entity **/
  317. class Product
  318. {
  319. // ...
  320. /**
  321. * @OneToMany(targetEntity="Feature", mappedBy="product")
  322. **/
  323. private $features;
  324. // ...
  325. public function __construct() {
  326. $this->features = new \Doctrine\Common\Collections\ArrayCollection();
  327. }
  328. }
  329. /** @Entity **/
  330. class Feature
  331. {
  332. // ...
  333. /**
  334. * @ManyToOne(targetEntity="Product", inversedBy="features")
  335. * @JoinColumn(name="product_id", referencedColumnName="id")
  336. **/
  337. private $product;
  338. // ...
  339. }
  340. .. code-block:: xml
  341. <doctrine-mapping>
  342. <entity name="Product">
  343. <one-to-many field="features" target-entity="Feature" mapped-by="product" />
  344. </entity>
  345. <entity name="Feature">
  346. <many-to-one field="product" target-entity="Product" inversed-by="features">
  347. <join-column name="product_id" referenced-column-name="id" />
  348. </many-to-one>
  349. </entity>
  350. </doctrine-mapping>
  351. .. code-block:: yaml
  352. Product:
  353. type: entity
  354. oneToMany:
  355. features:
  356. targetEntity: Feature
  357. mappedBy: product
  358. Feature:
  359. type: entity
  360. manyToOne:
  361. product:
  362. targetEntity: Product
  363. inversedBy: features
  364. joinColumn:
  365. name: product_id
  366. referencedColumnName: id
  367. Note that the @JoinColumn is not really necessary in this example,
  368. as the defaults would be the same.
  369. Generated MySQL Schema:
  370. .. code-block:: sql
  371. CREATE TABLE Product (
  372. id INT AUTO_INCREMENT NOT NULL,
  373. PRIMARY KEY(id)
  374. ) ENGINE = InnoDB;
  375. CREATE TABLE Feature (
  376. id INT AUTO_INCREMENT NOT NULL,
  377. product_id INT DEFAULT NULL,
  378. PRIMARY KEY(id)
  379. ) ENGINE = InnoDB;
  380. ALTER TABLE Feature ADD FOREIGN KEY (product_id) REFERENCES Product(id);
  381. One-To-Many, Self-referencing
  382. -----------------------------
  383. You can also setup a one-to-many association that is
  384. self-referencing. In this example we setup a hierarchy of
  385. ``Category`` objects by creating a self referencing relationship.
  386. This effectively models a hierarchy of categories and from the
  387. database perspective is known as an adjacency list approach.
  388. .. configuration-block::
  389. .. code-block:: php
  390. <?php
  391. /** @Entity **/
  392. class Category
  393. {
  394. // ...
  395. /**
  396. * @OneToMany(targetEntity="Category", mappedBy="parent")
  397. **/
  398. private $children;
  399. /**
  400. * @ManyToOne(targetEntity="Category", inversedBy="children")
  401. * @JoinColumn(name="parent_id", referencedColumnName="id")
  402. **/
  403. private $parent;
  404. // ...
  405. public function __construct() {
  406. $this->children = new \Doctrine\Common\Collections\ArrayCollection();
  407. }
  408. }
  409. .. code-block:: xml
  410. <doctrine-mapping>
  411. <entity name="Category">
  412. <one-to-many field="children" target-entity="Category" mapped-by="parent" />
  413. <many-to-one field="parent" target-entity="Category" inversed-by="children" />
  414. </entity>
  415. </doctrine-mapping>
  416. .. code-block:: yaml
  417. Category:
  418. type: entity
  419. oneToMany:
  420. children:
  421. targetEntity: Category
  422. mappedBy: parent
  423. manyToOne:
  424. parent:
  425. targetEntity: Category
  426. inversedBy: children
  427. Note that the @JoinColumn is not really necessary in this example,
  428. as the defaults would be the same.
  429. Generated MySQL Schema:
  430. .. code-block:: sql
  431. CREATE TABLE Category (
  432. id INT AUTO_INCREMENT NOT NULL,
  433. parent_id INT DEFAULT NULL,
  434. PRIMARY KEY(id)
  435. ) ENGINE = InnoDB;
  436. ALTER TABLE Category ADD FOREIGN KEY (parent_id) REFERENCES Category(id);
  437. Many-To-Many, Unidirectional
  438. ----------------------------
  439. Real many-to-many associations are less common. The following
  440. example shows a unidirectional association between User and Group
  441. entities:
  442. .. configuration-block::
  443. .. code-block:: php
  444. <?php
  445. /** @Entity **/
  446. class User
  447. {
  448. // ...
  449. /**
  450. * @ManyToMany(targetEntity="Group")
  451. * @JoinTable(name="users_groups",
  452. * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
  453. * inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")}
  454. * )
  455. **/
  456. private $groups;
  457. // ...
  458. public function __construct() {
  459. $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
  460. }
  461. }
  462. /** @Entity **/
  463. class Group
  464. {
  465. // ...
  466. }
  467. .. code-block:: xml
  468. <doctrine-mapping>
  469. <entity name="User">
  470. <many-to-many field="groups" target-entity="Group">
  471. <join-table name="users_groups">
  472. <join-columns>
  473. <join-column name="user_id" referenced-column-name="id" />
  474. </join-columns>
  475. <inverse-join-columns>
  476. <join-column name="group_id" referenced-column-name="id" />
  477. </inverse-join-columns>
  478. </join-table>
  479. </many-to-many>
  480. </entity>
  481. </doctrine-mapping>
  482. .. code-block:: yaml
  483. User:
  484. type: entity
  485. manyToMany:
  486. groups:
  487. targetEntity: Group
  488. joinTable:
  489. name: users_groups
  490. joinColumns:
  491. user_id:
  492. referencedColumnName: id
  493. inverseJoinColumns:
  494. group_id:
  495. referencedColumnName: id
  496. Generated MySQL Schema:
  497. .. code-block:: sql
  498. CREATE TABLE User (
  499. id INT AUTO_INCREMENT NOT NULL,
  500. PRIMARY KEY(id)
  501. ) ENGINE = InnoDB;
  502. CREATE TABLE users_groups (
  503. user_id INT NOT NULL,
  504. group_id INT NOT NULL,
  505. PRIMARY KEY(user_id, group_id)
  506. ) ENGINE = InnoDB;
  507. CREATE TABLE Group (
  508. id INT AUTO_INCREMENT NOT NULL,
  509. PRIMARY KEY(id)
  510. ) ENGINE = InnoDB;
  511. ALTER TABLE users_groups ADD FOREIGN KEY (user_id) REFERENCES User(id);
  512. ALTER TABLE users_groups ADD FOREIGN KEY (group_id) REFERENCES Group(id);
  513. .. note::
  514. Why are many-to-many associations less common? Because
  515. frequently you want to associate additional attributes with an
  516. association, in which case you introduce an association class.
  517. Consequently, the direct many-to-many association disappears and is
  518. replaced by one-to-many/many-to-one associations between the 3
  519. participating classes.
  520. Many-To-Many, Bidirectional
  521. ---------------------------
  522. Here is a similar many-to-many relationship as above except this
  523. one is bidirectional.
  524. .. configuration-block::
  525. .. code-block:: php
  526. <?php
  527. /** @Entity **/
  528. class User
  529. {
  530. // ...
  531. /**
  532. * @ManyToMany(targetEntity="Group", inversedBy="users")
  533. * @JoinTable(name="users_groups")
  534. **/
  535. private $groups;
  536. public function __construct() {
  537. $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
  538. }
  539. // ...
  540. }
  541. /** @Entity **/
  542. class Group
  543. {
  544. // ...
  545. /**
  546. * @ManyToMany(targetEntity="User", mappedBy="groups")
  547. **/
  548. private $users;
  549. public function __construct() {
  550. $this->users = new \Doctrine\Common\Collections\ArrayCollection();
  551. }
  552. // ...
  553. }
  554. .. code-block:: xml
  555. <doctrine-mapping>
  556. <entity name="User">
  557. <many-to-many field="groups" inversed-by="users" target-entity="Group">
  558. <join-table name="users_groups">
  559. <join-columns>
  560. <join-column name="user_id" referenced-column-name="id" />
  561. </join-columns>
  562. <inverse-join-columns>
  563. <join-column name="group_id" referenced-column-name="id" />
  564. </inverse-join-columns>
  565. </join-table>
  566. </many-to-many>
  567. </entity>
  568. <entity name="Group">
  569. <many-to-many field="users" mapped-by="groups" target-entity="User"/>
  570. </entity>
  571. </doctrine-mapping>
  572. .. code-block:: yaml
  573. User:
  574. type: entity
  575. manyToMany:
  576. groups:
  577. targetEntity: Group
  578. inversedBy: users
  579. joinTable:
  580. name: users_groups
  581. joinColumns:
  582. user_id:
  583. referencedColumnName: id
  584. inverseJoinColumns:
  585. group_id:
  586. referencedColumnName: id
  587. Group:
  588. type: entity
  589. manyToMany:
  590. users:
  591. targetEntity: User
  592. mappedBy: groups
  593. The MySQL schema is exactly the same as for the Many-To-Many
  594. uni-directional case above.
  595. Picking Owning and Inverse Side
  596. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  597. For Many-To-Many associations you can chose which entity is the
  598. owning and which the inverse side. There is a very simple semantic
  599. rule to decide which side is more suitable to be the owning side
  600. from a developers perspective. You only have to ask yourself, which
  601. entity is responsible for the connection management and pick that
  602. as the owning side.
  603. Take an example of two entities ``Article`` and ``Tag``. Whenever
  604. you want to connect an Article to a Tag and vice-versa, it is
  605. mostly the Article that is responsible for this relation. Whenever
  606. you add a new article, you want to connect it with existing or new
  607. tags. Your create Article form will probably support this notion
  608. and allow to specify the tags directly. This is why you should pick
  609. the Article as owning side, as it makes the code more
  610. understandable:
  611. .. code-block:: php
  612. <?php
  613. class Article
  614. {
  615. private $tags;
  616. public function addTag(Tag $tag)
  617. {
  618. $tag->addArticle($this); // synchronously updating inverse side
  619. $this->tags[] = $tag;
  620. }
  621. }
  622. class Tag
  623. {
  624. private $articles;
  625. public function addArticle(Article $article)
  626. {
  627. $this->articles[] = $article;
  628. }
  629. }
  630. This allows to group the tag adding on the ``Article`` side of the
  631. association:
  632. .. code-block:: php
  633. <?php
  634. $article = new Article();
  635. $article->addTag($tagA);
  636. $article->addTag($tagB);
  637. Many-To-Many, Self-referencing
  638. ------------------------------
  639. You can even have a self-referencing many-to-many association. A
  640. common scenario is where a ``User`` has friends and the target
  641. entity of that relationship is a ``User`` so it is self
  642. referencing. In this example it is bidirectional so ``User`` has a
  643. field named ``$friendsWithMe`` and ``$myFriends``.
  644. .. code-block:: php
  645. <?php
  646. /** @Entity **/
  647. class User
  648. {
  649. // ...
  650. /**
  651. * @ManyToMany(targetEntity="User", mappedBy="myFriends")
  652. **/
  653. private $friendsWithMe;
  654. /**
  655. * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
  656. * @JoinTable(name="friends",
  657. * joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
  658. * inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
  659. * )
  660. **/
  661. private $myFriends;
  662. public function __construct() {
  663. $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
  664. $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
  665. }
  666. // ...
  667. }
  668. Generated MySQL Schema:
  669. .. code-block:: sql
  670. CREATE TABLE User (
  671. id INT AUTO_INCREMENT NOT NULL,
  672. PRIMARY KEY(id)
  673. ) ENGINE = InnoDB;
  674. CREATE TABLE friends (
  675. user_id INT NOT NULL,
  676. friend_user_id INT NOT NULL,
  677. PRIMARY KEY(user_id, friend_user_id)
  678. ) ENGINE = InnoDB;
  679. ALTER TABLE friends ADD FOREIGN KEY (user_id) REFERENCES User(id);
  680. ALTER TABLE friends ADD FOREIGN KEY (friend_user_id) REFERENCES User(id);
  681. .. _association_mapping_defaults:
  682. Mapping Defaults
  683. ----------------
  684. Before we introduce all the association mappings in detail, you
  685. should note that the @JoinColumn and @JoinTable definitions are
  686. usually optional and have sensible default values. The defaults for
  687. a join column in a one-to-one/many-to-one association is as
  688. follows:
  689. ::
  690. name: "<fieldname>_id"
  691. referencedColumnName: "id"
  692. As an example, consider this mapping:
  693. .. configuration-block::
  694. .. code-block:: php
  695. <?php
  696. /** @OneToOne(targetEntity="Shipping") **/
  697. private $shipping;
  698. .. code-block:: xml
  699. <doctrine-mapping>
  700. <entity class="Product">
  701. <one-to-one field="shipping" target-entity="Shipping" />
  702. </entity>
  703. </doctrine-mapping>
  704. .. code-block:: yaml
  705. Product:
  706. type: entity
  707. oneToOne:
  708. shipping:
  709. targetEntity: Shipping
  710. This is essentially the same as the following, more verbose,
  711. mapping:
  712. .. configuration-block::
  713. .. code-block:: php
  714. <?php
  715. /**
  716. * @OneToOne(targetEntity="Shipping")
  717. * @JoinColumn(name="shipping_id", referencedColumnName="id")
  718. **/
  719. private $shipping;
  720. .. code-block:: xml
  721. <doctrine-mapping>
  722. <entity class="Product">
  723. <one-to-one field="shipping" target-entity="Shipping">
  724. <join-column name="shipping_id" referenced-column-name="id" />
  725. </one-to-one>
  726. </entity>
  727. </doctrine-mapping>
  728. .. code-block:: yaml
  729. Product:
  730. type: entity
  731. oneToOne:
  732. shipping:
  733. targetEntity: Shipping
  734. joinColumn:
  735. name: shipping_id
  736. referencedColumnName: id
  737. The @JoinTable definition used for many-to-many mappings has
  738. similar defaults. As an example, consider this mapping:
  739. .. configuration-block::
  740. .. code-block:: php
  741. <?php
  742. class User
  743. {
  744. //...
  745. /** @ManyToMany(targetEntity="Group") **/
  746. private $groups;
  747. //...
  748. }
  749. .. code-block:: xml
  750. <doctrine-mapping>
  751. <entity class="User">
  752. <many-to-many field="groups" target-entity="Group" />
  753. </entity>
  754. </doctrine-mapping>
  755. .. code-block:: yaml
  756. User:
  757. type: entity
  758. manyToMany:
  759. groups:
  760. targetEntity: Group
  761. This is essentially the same as the following, more verbose,
  762. mapping:
  763. .. configuration-block::
  764. .. code-block:: php
  765. <?php
  766. class User
  767. {
  768. //...
  769. /**
  770. * @ManyToMany(targetEntity="Group")
  771. * @JoinTable(name="User_Group",
  772. * joinColumns={@JoinColumn(name="User_id", referencedColumnName="id")},
  773. * inverseJoinColumns={@JoinColumn(name="Group_id", referencedColumnName="id")}
  774. * )
  775. **/
  776. private $groups;
  777. //...
  778. }
  779. .. code-block:: xml
  780. <doctrine-mapping>
  781. <entity class="User">
  782. <many-to-many field="groups" target-entity="Group">
  783. <join-table name="User_Group">
  784. <join-columns>
  785. <join-column id="User_id" referenced-column-name="id" />
  786. </join-columns>
  787. <inverse-join-columns>
  788. <join-column id="Group_id" referenced-column-name="id" />
  789. </inverse-join-columns>
  790. </join-table>
  791. </many-to-many>
  792. </entity>
  793. </doctrine-mapping>
  794. .. code-block:: yaml
  795. User:
  796. type: entity
  797. manyToMany:
  798. groups:
  799. targetEntity: Group
  800. joinTable:
  801. name: User_Group
  802. joinColumns:
  803. User_id:
  804. referencedColumnName: id
  805. inverseJoinColumns:
  806. Group_id:
  807. referencedColumnName: id
  808. In that case, the name of the join table defaults to a combination
  809. of the simple, unqualified class names of the participating
  810. classes, separated by an underscore character. The names of the
  811. join columns default to the simple, unqualified class name of the
  812. targeted class followed by "\_id". The referencedColumnName always
  813. defaults to "id", just as in one-to-one or many-to-one mappings.
  814. If you accept these defaults, you can reduce the mapping code to a
  815. minimum.
  816. .. _collections:
  817. Collections
  818. -----------
  819. In all the examples of many-valued associations in this manual we
  820. will make use of a ``Collection`` interface and a corresponding
  821. default implementation ``ArrayCollection`` that are defined in the
  822. ``Doctrine\Common\Collections`` namespace. Why do we need that?
  823. Doesn't that couple my domain model to Doctrine? Unfortunately, PHP
  824. arrays, while being great for many things, do not make up for good
  825. collections of business objects, especially not in the context of
  826. an ORM. The reason is that plain PHP arrays can not be
  827. transparently extended / instrumented in PHP code, which is
  828. necessary for a lot of advanced ORM features. The classes /
  829. interfaces that come closest to an OO collection are ArrayAccess
  830. and ArrayObject but until instances of these types can be used in
  831. all places where a plain array can be used (something that may
  832. happen in PHP6) their usability is fairly limited. You "can"
  833. type-hint on ``ArrayAccess`` instead of ``Collection``, since the
  834. Collection interface extends ``ArrayAccess``, but this will
  835. severely limit you in the way you can work with the collection,
  836. because the ``ArrayAccess`` API is (intentionally) very primitive
  837. and more importantly because you can not pass this collection to
  838. all the useful PHP array functions, which makes it very hard to
  839. work with.
  840. .. warning::
  841. The Collection interface and ArrayCollection class,
  842. like everything else in the Doctrine namespace, are neither part of
  843. the ORM, nor the DBAL, it is a plain PHP class that has no outside
  844. dependencies apart from dependencies on PHP itself (and the SPL).
  845. Therefore using this class in your domain classes and elsewhere
  846. does not introduce a coupling to the persistence layer. The
  847. Collection class, like everything else in the Common namespace, is
  848. not part of the persistence layer. You could even copy that class
  849. over to your project if you want to remove Doctrine from your
  850. project and all your domain classes will work the same as before.
  851. Initializing Collections
  852. ------------------------
  853. You have to be careful when using entity fields that contain a
  854. collection of related entities. Say we have a User entity that
  855. contains a collection of groups:
  856. .. code-block:: php
  857. <?php
  858. /** @Entity **/
  859. class User
  860. {
  861. /** @ManyToMany(targetEntity="Group") **/
  862. private $groups;
  863. public function getGroups()
  864. {
  865. return $this->groups;
  866. }
  867. }
  868. With this code alone the ``$groups`` field only contains an
  869. instance of ``Doctrine\Common\Collections\Collection`` if the user
  870. is retrieved from Doctrine, however not after you instantiated a
  871. fresh instance of the User. When your user entity is still new
  872. ``$groups`` will obviously be null.
  873. This is why we recommend to initialize all collection fields to an
  874. empty ``ArrayCollection`` in your entities constructor:
  875. .. code-block:: php
  876. <?php
  877. use Doctrine\Common\Collections\ArrayCollection;
  878. /** @Entity **/
  879. class User
  880. {
  881. /** @ManyToMany(targetEntity="Group") **/
  882. private $groups;
  883. public function __construct()
  884. {
  885. $this->groups = new ArrayCollection();
  886. }
  887. public function getGroups()
  888. {
  889. return $this->groups;
  890. }
  891. }
  892. Now the following code will work even if the Entity hasn't
  893. been associated with an EntityManager yet:
  894. .. code-block:: php
  895. <?php
  896. $group = $entityManager->find('Group', $groupId);
  897. $user = new User();
  898. $user->getGroups()->add($group);