File: association-mapping.rst

package info (click to toggle)
doctrine 2.4.6-1%2Bdeb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 3,576 kB
  • ctags: 6,179
  • sloc: php: 24,243; makefile: 101; python: 81; sh: 10
file content (1145 lines) | stat: -rw-r--r-- 32,020 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
Association Mapping
===================

This chapter introduces association mappings which are used to explain
references between objects and are mapped to a relational database using
foreign keys.

Instead of working with the foreign keys directly you will always work with
references to objects:

- A reference to a single object is represented by a foreign key.
- A collection of objects is represented by many foreign keys pointing to the object holding the collection

This chapter is split into three different sections.

- A list of all the possible association mapping use-cases is given.
- :ref:`association_mapping_defaults` are explained that simplify the use-case examples.
- :ref:`collections` are introduced that contain entities in associations.

To master associations you should also learn about :doc:`owning and inverse sides of associations <unitofwork-associations>`

One-To-One, Unidirectional
--------------------------

A unidirectional one-to-one association is very common. Here is an
example of a ``Product`` that has one ``Shipping`` object
associated to it. The ``Shipping`` side does not reference back to
the ``Product`` so it is unidirectional.

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class Product
        {
            // ...

            /**
             * @OneToOne(targetEntity="Shipping")
             * @JoinColumn(name="shipping_id", referencedColumnName="id")
             **/
            private $shipping;

            // ...
        }

        /** @Entity **/
        class Shipping
        {
            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity class="Product">
                <one-to-one field="shipping" target-entity="Shipping">
                    <join-column name="shipping_id" referenced-column-name="id" />
                </one-to-one>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Product:
          type: entity
          oneToOne:
            shipping:
              targetEntity: Shipping
              joinColumn:
                name: shipping_id
                referencedColumnName: id

Note that the @JoinColumn is not really necessary in this example,
as the defaults would be the same.

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE Product (
        id INT AUTO_INCREMENT NOT NULL,
        shipping_id INT DEFAULT NULL,
        UNIQUE INDEX UNIQ_6FBC94267FE4B2B (shipping_id),
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    CREATE TABLE Shipping (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Product ADD FOREIGN KEY (shipping_id) REFERENCES Shipping(id);

One-To-One, Bidirectional
-------------------------

Here is a one-to-one relationship between a ``Customer`` and a
``Cart``. The ``Cart`` has a reference back to the ``Customer`` so
it is bidirectional.

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class Customer
        {
            // ...

            /**
             * @OneToOne(targetEntity="Cart", mappedBy="customer")
             **/
            private $cart;

            // ...
        }

        /** @Entity **/
        class Cart
        {
            // ...

            /**
             * @OneToOne(targetEntity="Customer", inversedBy="cart")
             * @JoinColumn(name="customer_id", referencedColumnName="id")
             **/
            private $customer;

            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="Customer">
                <one-to-one field="cart" target-entity="Cart" mapped-by="customer" />
            </entity>
            <entity name="Cart">
                <one-to-one field="customer" target-entity="Customer" inversed-by="cart">
                    <join-column name="customer_id" referenced-column-name="id" />
                </one-to-one>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Customer:
          oneToOne:
            cart:
              targetEntity: Cart
              mappedBy: customer
        Cart:
          oneToOne:
            customer:
              targetEntity: Customer
              inversedBy: cart
              joinColumn:
                name: customer_id
                referencedColumnName: id

Note that the @JoinColumn is not really necessary in this example,
as the defaults would be the same.

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE Cart (
        id INT AUTO_INCREMENT NOT NULL,
        customer_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    CREATE TABLE Customer (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Cart ADD FOREIGN KEY (customer_id) REFERENCES Customer(id);

See how the foreign key is defined on the owning side of the
relation, the table ``Cart``.

One-To-One, Self-referencing
----------------------------

You can easily have self referencing one-to-one relationships like
below.

.. code-block:: php

    <?php
    /** @Entity **/
    class Student
    {
        // ...

        /**
         * @OneToOne(targetEntity="Student")
         * @JoinColumn(name="mentor_id", referencedColumnName="id")
         **/
        private $mentor;

        // ...
    }

Note that the @JoinColumn is not really necessary in this example,
as the defaults would be the same.

With the generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE Student (
        id INT AUTO_INCREMENT NOT NULL,
        mentor_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Student ADD FOREIGN KEY (mentor_id) REFERENCES Student(id);

One-To-Many, Unidirectional with Join Table
-------------------------------------------

A unidirectional one-to-many association can be mapped through a
join table. From Doctrine's point of view, it is simply mapped as a
unidirectional many-to-many whereby a unique constraint on one of
the join columns enforces the one-to-many cardinality.

.. note::

    One-To-Many uni-directional relations with join-table only
    work using the @ManyToMany annotation and a unique-constraint.


The following example sets up such a unidirectional one-to-many association:

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class User
        {
            // ...

            /**
             * @ManyToMany(targetEntity="Phonenumber")
             * @JoinTable(name="users_phonenumbers",
             *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
             *      inverseJoinColumns={@JoinColumn(name="phonenumber_id", referencedColumnName="id", unique=true)}
             *      )
             **/
            private $phonenumbers;

            public function __construct()
            {
                $this->phonenumbers = new \Doctrine\Common\Collections\ArrayCollection();
            }

            // ...
        }

        /** @Entity **/
        class Phonenumber
        {
            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="User">
                <many-to-many field="phonenumbers" target-entity="Phonenumber">
                    <join-table name="users_phonenumbers">
                        <join-columns>
                            <join-column name="user_id" referenced-column-name="id" />
                        </join-columns>
                        <inverse-join-columns>
                            <join-column name="phonenumber_id" referenced-column-name="id" unique="true" />
                        </inverse-join-columns>
                    </join-table>
                </many-to-many>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToMany:
            phonenumbers:
              targetEntity: Phonenumber
              joinTable:
                name: users_phonenumbers
                joinColumns:
                  user_id:
                    referencedColumnName: id
                inverseJoinColumns:
                  phonenumber_id:
                    referencedColumnName: id
                    unique: true


Generates the following MySQL Schema:

.. code-block:: sql

    CREATE TABLE User (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;

    CREATE TABLE users_phonenumbers (
        user_id INT NOT NULL,
        phonenumber_id INT NOT NULL,
        UNIQUE INDEX users_phonenumbers_phonenumber_id_uniq (phonenumber_id),
        PRIMARY KEY(user_id, phonenumber_id)
    ) ENGINE = InnoDB;

    CREATE TABLE Phonenumber (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;

    ALTER TABLE users_phonenumbers ADD FOREIGN KEY (user_id) REFERENCES User(id);
    ALTER TABLE users_phonenumbers ADD FOREIGN KEY (phonenumber_id) REFERENCES Phonenumber(id);


Many-To-One, Unidirectional
---------------------------

You can easily implement a many-to-one unidirectional association
with the following:

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class User
        {
            // ...

            /**
             * @ManyToOne(targetEntity="Address")
             * @JoinColumn(name="address_id", referencedColumnName="id")
             **/
            private $address;
        }

        /** @Entity **/
        class Address
        {
            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="User">
                <many-to-one field="address" target-entity="Address">
                    <join-column name="address_id" referenced-column-name="id" />
                </many-to-one>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToOne:
            address:
              targetEntity: Address
              joinColumn:
                name: address_id
                referencedColumnName: id


.. note::

    The above ``@JoinColumn`` is optional as it would default
    to ``address_id`` and ``id`` anyways. You can omit it and let it
    use the defaults.


Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE User (
        id INT AUTO_INCREMENT NOT NULL,
        address_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;

    CREATE TABLE Address (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;

    ALTER TABLE User ADD FOREIGN KEY (address_id) REFERENCES Address(id);

One-To-Many, Bidirectional
--------------------------

Bidirectional one-to-many associations are very common. The
following code shows an example with a Product and a Feature
class:

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class Product
        {
            // ...
            /**
             * @OneToMany(targetEntity="Feature", mappedBy="product")
             **/
            private $features;
            // ...

            public function __construct() {
                $this->features = new \Doctrine\Common\Collections\ArrayCollection();
            }
        }

        /** @Entity **/
        class Feature
        {
            // ...
            /**
             * @ManyToOne(targetEntity="Product", inversedBy="features")
             * @JoinColumn(name="product_id", referencedColumnName="id")
             **/
            private $product;
            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="Product">
                <one-to-many field="features" target-entity="Feature" mapped-by="product" />
            </entity>
            <entity name="Feature">
                <many-to-one field="product" target-entity="Product" inversed-by="features">
                    <join-column name="product_id" referenced-column-name="id" />
                </many-to-one>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Product:
          type: entity
          oneToMany:
            features:
              targetEntity: Feature
              mappedBy: product
        Feature:
          type: entity
          manyToOne:
            product:
              targetEntity: Product
              inversedBy: features
              joinColumn:
                name: product_id
                referencedColumnName: id


Note that the @JoinColumn is not really necessary in this example,
as the defaults would be the same.

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE Product (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    CREATE TABLE Feature (
        id INT AUTO_INCREMENT NOT NULL,
        product_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Feature ADD FOREIGN KEY (product_id) REFERENCES Product(id);

One-To-Many, Self-referencing
-----------------------------

You can also setup a one-to-many association that is
self-referencing. In this example we setup a hierarchy of
``Category`` objects by creating a self referencing relationship.
This effectively models a hierarchy of categories and from the
database perspective is known as an adjacency list approach.

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class Category
        {
            // ...
            /**
             * @OneToMany(targetEntity="Category", mappedBy="parent")
             **/
            private $children;

            /**
             * @ManyToOne(targetEntity="Category", inversedBy="children")
             * @JoinColumn(name="parent_id", referencedColumnName="id")
             **/
            private $parent;
            // ...

            public function __construct() {
                $this->children = new \Doctrine\Common\Collections\ArrayCollection();
            }
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="Category">
                <one-to-many field="children" target-entity="Category" mapped-by="parent" />
                <many-to-one field="parent" target-entity="Category" inversed-by="children" />
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Category:
          type: entity
          oneToMany:
            children:
              targetEntity: Category
              mappedBy: parent
          manyToOne:
            parent:
              targetEntity: Category
              inversedBy: children

Note that the @JoinColumn is not really necessary in this example,
as the defaults would be the same.

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE Category (
        id INT AUTO_INCREMENT NOT NULL,
        parent_id INT DEFAULT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE Category ADD FOREIGN KEY (parent_id) REFERENCES Category(id);

Many-To-Many, Unidirectional
----------------------------

Real many-to-many associations are less common. The following
example shows a unidirectional association between User and Group
entities:

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class User
        {
            // ...

            /**
             * @ManyToMany(targetEntity="Group")
             * @JoinTable(name="users_groups",
             *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
             *      inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id")}
             *      )
             **/
            private $groups;

            // ...

            public function __construct() {
                $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
            }
        }

        /** @Entity **/
        class Group
        {
            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="User">
                <many-to-many field="groups" target-entity="Group">
                    <join-table name="users_groups">
                        <join-columns>
                            <join-column name="user_id" referenced-column-name="id" />
                        </join-columns>
                        <inverse-join-columns>
                            <join-column name="group_id" referenced-column-name="id" />
                        </inverse-join-columns>
                    </join-table>
                </many-to-many>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToMany:
            groups:
              targetEntity: Group
              joinTable:
                name: users_groups
                joinColumns:
                  user_id:
                    referencedColumnName: id
                inverseJoinColumns:
                  group_id:
                    referencedColumnName: id

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE User (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    CREATE TABLE users_groups (
        user_id INT NOT NULL,
        group_id INT NOT NULL,
        PRIMARY KEY(user_id, group_id)
    ) ENGINE = InnoDB;
    CREATE TABLE Group (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    ALTER TABLE users_groups ADD FOREIGN KEY (user_id) REFERENCES User(id);
    ALTER TABLE users_groups ADD FOREIGN KEY (group_id) REFERENCES Group(id);

.. note::

    Why are many-to-many associations less common? Because
    frequently you want to associate additional attributes with an
    association, in which case you introduce an association class.
    Consequently, the direct many-to-many association disappears and is
    replaced by one-to-many/many-to-one associations between the 3
    participating classes.

Many-To-Many, Bidirectional
---------------------------

Here is a similar many-to-many relationship as above except this
one is bidirectional.

.. configuration-block::

    .. code-block:: php

        <?php
        /** @Entity **/
        class User
        {
            // ...

            /**
             * @ManyToMany(targetEntity="Group", inversedBy="users")
             * @JoinTable(name="users_groups")
             **/
            private $groups;

            public function __construct() {
                $this->groups = new \Doctrine\Common\Collections\ArrayCollection();
            }

            // ...
        }

        /** @Entity **/
        class Group
        {
            // ...
            /**
             * @ManyToMany(targetEntity="User", mappedBy="groups")
             **/
            private $users;

            public function __construct() {
                $this->users = new \Doctrine\Common\Collections\ArrayCollection();
            }

            // ...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity name="User">
                <many-to-many field="groups" inversed-by="users" target-entity="Group">
                    <join-table name="users_groups">
                        <join-columns>
                            <join-column name="user_id" referenced-column-name="id" />
                        </join-columns>
                        <inverse-join-columns>
                            <join-column name="group_id" referenced-column-name="id" />
                        </inverse-join-columns>
                    </join-table>
                </many-to-many>
            </entity>

            <entity name="Group">
                <many-to-many field="users" mapped-by="groups" target-entity="User"/>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToMany:
            groups:
              targetEntity: Group
              inversedBy: users
              joinTable:
                name: users_groups
                joinColumns:
                  user_id:
                    referencedColumnName: id
                inverseJoinColumns:
                  group_id:
                    referencedColumnName: id

        Group:
          type: entity
          manyToMany:
            users:
              targetEntity: User
              mappedBy: groups

The MySQL schema is exactly the same as for the Many-To-Many
uni-directional case above.

Picking Owning and Inverse Side
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

For Many-To-Many associations you can chose which entity is the
owning and which the inverse side. There is a very simple semantic
rule to decide which side is more suitable to be the owning side
from a developers perspective. You only have to ask yourself, which
entity is responsible for the connection management and pick that
as the owning side.

Take an example of two entities ``Article`` and ``Tag``. Whenever
you want to connect an Article to a Tag and vice-versa, it is
mostly the Article that is responsible for this relation. Whenever
you add a new article, you want to connect it with existing or new
tags. Your create Article form will probably support this notion
and allow to specify the tags directly. This is why you should pick
the Article as owning side, as it makes the code more
understandable:

.. code-block:: php

    <?php
    class Article
    {
        private $tags;

        public function addTag(Tag $tag)
        {
            $tag->addArticle($this); // synchronously updating inverse side
            $this->tags[] = $tag;
        }
    }

    class Tag
    {
        private $articles;

        public function addArticle(Article $article)
        {
            $this->articles[] = $article;
        }
    }

This allows to group the tag adding on the ``Article`` side of the
association:

.. code-block:: php

    <?php
    $article = new Article();
    $article->addTag($tagA);
    $article->addTag($tagB);

Many-To-Many, Self-referencing
------------------------------

You can even have a self-referencing many-to-many association. A
common scenario is where a ``User`` has friends and the target
entity of that relationship is a ``User`` so it is self
referencing. In this example it is bidirectional so ``User`` has a
field named ``$friendsWithMe`` and ``$myFriends``.

.. code-block:: php

    <?php
    /** @Entity **/
    class User
    {
        // ...

        /**
         * @ManyToMany(targetEntity="User", mappedBy="myFriends")
         **/
        private $friendsWithMe;

        /**
         * @ManyToMany(targetEntity="User", inversedBy="friendsWithMe")
         * @JoinTable(name="friends",
         *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
         *      inverseJoinColumns={@JoinColumn(name="friend_user_id", referencedColumnName="id")}
         *      )
         **/
        private $myFriends;

        public function __construct() {
            $this->friendsWithMe = new \Doctrine\Common\Collections\ArrayCollection();
            $this->myFriends = new \Doctrine\Common\Collections\ArrayCollection();
        }

        // ...
    }

Generated MySQL Schema:

.. code-block:: sql

    CREATE TABLE User (
        id INT AUTO_INCREMENT NOT NULL,
        PRIMARY KEY(id)
    ) ENGINE = InnoDB;
    CREATE TABLE friends (
        user_id INT NOT NULL,
        friend_user_id INT NOT NULL,
        PRIMARY KEY(user_id, friend_user_id)
    ) ENGINE = InnoDB;
    ALTER TABLE friends ADD FOREIGN KEY (user_id) REFERENCES User(id);
    ALTER TABLE friends ADD FOREIGN KEY (friend_user_id) REFERENCES User(id);

.. _association_mapping_defaults:

Mapping Defaults
----------------

Before we introduce all the association mappings in detail, you
should note that the @JoinColumn and @JoinTable definitions are
usually optional and have sensible default values. The defaults for
a join column in a one-to-one/many-to-one association is as
follows:

::

    name: "<fieldname>_id"
    referencedColumnName: "id"

As an example, consider this mapping:

.. configuration-block::

    .. code-block:: php

        <?php
        /** @OneToOne(targetEntity="Shipping") **/
        private $shipping;

    .. code-block:: xml

        <doctrine-mapping>
            <entity class="Product">
                <one-to-one field="shipping" target-entity="Shipping" />
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Product:
          type: entity
          oneToOne:
            shipping:
              targetEntity: Shipping

This is essentially the same as the following, more verbose,
mapping:

.. configuration-block::

    .. code-block:: php

        <?php
        /**
         * @OneToOne(targetEntity="Shipping")
         * @JoinColumn(name="shipping_id", referencedColumnName="id")
         **/
        private $shipping;

    .. code-block:: xml

        <doctrine-mapping>
            <entity class="Product">
                <one-to-one field="shipping" target-entity="Shipping">
                    <join-column name="shipping_id" referenced-column-name="id" />
                </one-to-one>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        Product:
          type: entity
          oneToOne:
            shipping:
              targetEntity: Shipping
              joinColumn:
                name: shipping_id
                referencedColumnName: id

The @JoinTable definition used for many-to-many mappings has
similar defaults. As an example, consider this mapping:

.. configuration-block::

    .. code-block:: php

        <?php
        class User
        {
            //...
            /** @ManyToMany(targetEntity="Group") **/
            private $groups;
            //...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity class="User">
                <many-to-many field="groups" target-entity="Group" />
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToMany:
            groups:
              targetEntity: Group

This is essentially the same as the following, more verbose,
mapping:

.. configuration-block::

    .. code-block:: php

        <?php
        class User
        {
            //...
            /**
             * @ManyToMany(targetEntity="Group")
             * @JoinTable(name="User_Group",
             *      joinColumns={@JoinColumn(name="User_id", referencedColumnName="id")},
             *      inverseJoinColumns={@JoinColumn(name="Group_id", referencedColumnName="id")}
             *      )
             **/
            private $groups;
            //...
        }

    .. code-block:: xml

        <doctrine-mapping>
            <entity class="User">
                <many-to-many field="groups" target-entity="Group">
                    <join-table name="User_Group">
                        <join-columns>
                            <join-column id="User_id" referenced-column-name="id" />
                        </join-columns>
                        <inverse-join-columns>
                            <join-column id="Group_id" referenced-column-name="id" />
                        </inverse-join-columns>
                    </join-table>
                </many-to-many>
            </entity>
        </doctrine-mapping>

    .. code-block:: yaml

        User:
          type: entity
          manyToMany:
            groups:
              targetEntity: Group
              joinTable:
                name: User_Group
                joinColumns:
                  User_id:
                    referencedColumnName: id
                inverseJoinColumns:
                  Group_id:
                    referencedColumnName: id

In that case, the name of the join table defaults to a combination
of the simple, unqualified class names of the participating
classes, separated by an underscore character. The names of the
join columns default to the simple, unqualified class name of the
targeted class followed by "\_id". The referencedColumnName always
defaults to "id", just as in one-to-one or many-to-one mappings.

If you accept these defaults, you can reduce the mapping code to a
minimum.

.. _collections:

Collections
-----------

In all the examples of many-valued associations in this manual we
will make use of a ``Collection`` interface and a corresponding
default implementation ``ArrayCollection`` that are defined in the
``Doctrine\Common\Collections`` namespace. Why do we need that?
Doesn't that couple my domain model to Doctrine? Unfortunately, PHP
arrays, while being great for many things, do not make up for good
collections of business objects, especially not in the context of
an ORM. The reason is that plain PHP arrays can not be
transparently extended / instrumented in PHP code, which is
necessary for a lot of advanced ORM features. The classes /
interfaces that come closest to an OO collection are ArrayAccess
and ArrayObject but until instances of these types can be used in
all places where a plain array can be used (something that may
happen in PHP6) their usability is fairly limited. You "can"
type-hint on ``ArrayAccess`` instead of ``Collection``, since the
Collection interface extends ``ArrayAccess``, but this will
severely limit you in the way you can work with the collection,
because the ``ArrayAccess`` API is (intentionally) very primitive
and more importantly because you can not pass this collection to
all the useful PHP array functions, which makes it very hard to
work with.

.. warning::

    The Collection interface and ArrayCollection class,
    like everything else in the Doctrine namespace, are neither part of
    the ORM, nor the DBAL, it is a plain PHP class that has no outside
    dependencies apart from dependencies on PHP itself (and the SPL).
    Therefore using this class in your domain classes and elsewhere
    does not introduce a coupling to the persistence layer. The
    Collection class, like everything else in the Common namespace, is
    not part of the persistence layer. You could even copy that class
    over to your project if you want to remove Doctrine from your
    project and all your domain classes will work the same as before.



Initializing Collections
------------------------

You have to be careful when using entity fields that contain a
collection of related entities. Say we have a User entity that
contains a collection of groups:

.. code-block:: php

    <?php
    /** @Entity **/
    class User
    {
        /** @ManyToMany(targetEntity="Group") **/
        private $groups;

        public function getGroups()
        {
            return $this->groups;
        }
    }

With this code alone the ``$groups`` field only contains an
instance of ``Doctrine\Common\Collections\Collection`` if the user
is retrieved from Doctrine, however not after you instantiated a
fresh instance of the User. When your user entity is still new
``$groups`` will obviously be null.

This is why we recommend to initialize all collection fields to an
empty ``ArrayCollection`` in your entities constructor:

.. code-block:: php

    <?php
    use Doctrine\Common\Collections\ArrayCollection;

    /** @Entity **/
    class User
    {
        /** @ManyToMany(targetEntity="Group") **/
        private $groups;

        public function __construct()
        {
            $this->groups = new ArrayCollection();
        }

        public function getGroups()
        {
            return $this->groups;
        }
    }

Now the following code will work even if the Entity hasn't
been associated with an EntityManager yet:

.. code-block:: php

    <?php
    $group = $entityManager->find('Group', $groupId);
    $user = new User();
    $user->getGroups()->add($group);