Symfony2 desde 0: Relaciones en Doctrine

Hemos generado las entidades automáticamente y también hemos indicado que la definición de estas estará en archivos yml. Ahora vamos a ver las relaciones en Doctrine que utilizaremos para el blog.

Src/Web/BlogBundle/Resources/config/doctrine/Posts.orm.yml aquí tenemos la definición de cada campo y de las relaciones.

1Web\BlogBundle\Entity\Posts:
2    type: entity
3    table: posts
4    indexes:
5        fk_category_post:
6            columns:
7                - category_id
8        fk_user_post:
9            columns:
10                - user_id
11    id:
12        id:
13            type: bigint
14            nullable: false
15            unsigned: false
16            id: true
17            generator:
18                strategy: IDENTITY
19    fields:
20        title:
21            type: string
22            nullable: true
23            length: 255
24            fixed: false
25        description:
26            type: string
27            nullable: true
28            length: 255
29            fixed: false
30        image:
31            type: string
32            nullable: true
33            length: 255
34            fixed: false
35        content:
36            type: string
37            nullable: true
38            length: 255
39            fixed: false
40        status:
41            type: string
42            nullable: true
43            length: 50
44            fixed: false
45        date:
46            type: date
47            nullable: true
48        time:
49            type: time
50            nullable: true
51 
52    manyToOne:
53        #Relación de muchos a uno, muchos posts para una categoria
54        category:
55            targetEntity: Categories
56            cascade: {  }
57            mappedBy: null
58            inversedBy: posts
59            joinColumns:
60                category_id:
61                    referencedColumnName: id
62            orphanRemoval: false
63 
64        #Relación de muchos a uno, muchos posts de un usuario
65        user:
66            targetEntity: Users
67            cascade: {  }
68            mappedBy: null
69            inversedBy: posts
70            joinColumns:
71                user_id:
72                    referencedColumnName: id
73            orphanRemoval: false
74 
75#Añadimos la relación oneToMany
76    oneToMany:
77        #Relación de uno a muchos, un post puede tener muchas tags
78        tagsPosts:
79            targetEntity: TagsPosts
80            mappedBy: post
81            cascade: ["persist"]
82    lifecycleCallbacks: {  }

En el yml de TagsPosts:

1Web\BlogBundle\Entity\TagsPosts:
2    type: entity
3    table: tags_posts
4    indexes:
5        fk_tag_id_tp:
6            columns:
7                - tag_id
8        fk_post_id_tp:
9            columns:
10                - post_id
11    id:
12        id:
13            type: bigint
14            nullable: false
15            unsigned: false
16            id: true
17            generator:
18                strategy: IDENTITY
19    manyToOne:
20        tag:
21            targetEntity: Tags
22            cascade: {  }
23            mappedBy: null
24            inversedBy: null
25            joinColumns:
26                tag_id:
27                    referencedColumnName: id
28            orphanRemoval: false
29        post:
30            targetEntity: Posts
31            cascade: {  }
32            mappedBy: null
33#Tenemos que añadir el inversedBy
34            inversedBy: tagsPosts
35            joinColumns:
36                post_id:
37                    referencedColumnName: id
38            orphanRemoval: false
39    lifecycleCallbacks: {  }

Ahora modificaremos la entidad src/Web/BlogBundle/Entity/Posts.php, le añadiremos métodos para la relación OneToMany.

1<?php
2 
3namespace Web\BlogBundle\Entity;
4 
5use Doctrine\ORM\Mapping as ORM;
6use Doctrine\Common\Collections\ArrayCollection;
7 
8/**
9 * Posts
10 */
11class Posts {
12 
13    /**
14     * @var integer
15     */
16    private $id;
17 
18    /**
19     * @var string
20     */
21    private $title;
22 
23    /**
24     * @var string
25     */
26    private $description;
27 
28    /**
29     * @var string
30     */
31    private $image;
32 
33    /**
34     * @var string
35     */
36    private $content;
37 
38    /**
39     * @var string
40     */
41    private $status;
42 
43    /**
44     * @var \DateTime
45     */
46    private $date;
47 
48    /**
49     * @var \DateTime
50     */
51    private $time;
52 
53    /**
54     * @var \Web\BlogBundle\Entity\Categories
55     */
56    private $category;
57 
58    /**
59     * @var \Web\BlogBundle\Entity\Users
60     */
61    private $user;
62 
63//Añadimos la propiedad $tagsPosts
64    /**
65     * @var \Web\BlogBundle\Entity\TagsPosts
66     */
67    protected $tagsPosts;
68 
69    public function __construct() {
70        $this->tagsPosts = new ArrayCollection();
71    }
72 
73    /**
74     * Get id
75     *
76     * @return integer
77     */
78    public function getId() {
79        return $this->id;
80    }
81 
82    /**
83     * Set title
84     *
85     * @param string $title
86     * @return Posts
87     */
88    public function setTitle($title) {
89        $this->title = $title;
90 
91        return $this;
92    }
93 
94    /**
95     * Get title
96     *
97     * @return string
98     */
99    public function getTitle() {
100        return $this->title;
101    }
102 
103    /**
104     * Set description
105     *
106     * @param string $description
107     * @return Posts
108     */
109    public function setDescription($description) {
110        $this->description = $description;
111 
112        return $this;
113    }
114 
115    /**
116     * Get description
117     *
118     * @return string
119     */
120    public function getDescription() {
121        return $this->description;
122    }
123 
124    /**
125     * Set image
126     *
127     * @param string $image
128     * @return Posts
129     */
130    public function setImage($image) {
131        $this->image = $image;
132 
133        return $this;
134    }
135 
136    /**
137     * Get image
138     *
139     * @return string
140     */
141    public function getImage() {
142        return $this->image;
143    }
144 
145    /**
146     * Set content
147     *
148     * @param string $content
149     * @return Posts
150     */
151    public function setContent($content) {
152        $this->content = $content;
153 
154        return $this;
155    }
156 
157    /**
158     * Get content
159     *
160     * @return string
161     */
162    public function getContent() {
163        return $this->content;
164    }
165 
166    /**
167     * Set status
168     *
169     * @param string $status
170     * @return Posts
171     */
172    public function setStatus($status) {
173        $this->status = $status;
174 
175        return $this;
176    }
177 
178    /**
179     * Get status
180     *
181     * @return string
182     */
183    public function getStatus() {
184        return $this->status;
185    }
186 
187    /**
188     * Set date
189     *
190     * @param \DateTime $date
191     * @return Posts
192     */
193    public function setDate($date) {
194        $this->date = $date;
195 
196        return $this;
197    }
198 
199    /**
200     * Get date
201     *
202     * @return \DateTime
203     */
204    public function getDate() {
205        return $this->date;
206    }
207 
208    /**
209     * Set time
210     *
211     * @param \DateTime $time
212     * @return Posts
213     */
214    public function setTime($time) {
215        $this->time = $time;
216 
217        return $this;
218    }
219 
220    /**
221     * Get time
222     *
223     * @return \DateTime
224     */
225    public function getTime() {
226        return $this->time;
227    }
228 
229    /**
230     * Set category
231     *
232     * @param \Web\BlogBundle\Entity\Categories $category
233     * @return Posts
234     */
235    public function setCategory(\Web\BlogBundle\Entity\Categories $category = null) {
236        $this->category = $category;
237 
238        return $this;
239    }
240 
241    /**
242     * Get category
243     *
244     * @return \Web\BlogBundle\Entity\Categories
245     */
246    public function getCategory() {
247        return $this->category;
248    }
249 
250    /**
251     * Set user
252     *
253     * @param \Web\BlogBundle\Entity\Users $user
254     * @return Posts
255     */
256    public function setUser(\Web\BlogBundle\Entity\Users $user = null) {
257        $this->user = $user;
258 
259        return $this;
260    }
261 
262    /**
263     * Get user
264     *
265     * @return \Web\BlogBundle\Entity\Users
266     */
267    public function getUser() {
268        return $this->user;
269    }
270 
271/* Añadimos estos dos métodos, aunque solamente utilizaremos el segundo para conseguir todas las tags de un post con una instancia de post. */
272    /**
273     * Add tagsPosts
274     *
275     * @param  Tag $tag
276     * @return Course
277     */
278    public function addTagsPosts(\Web\BlogBundle\Entity\Tags $tag) {
279        $this->tagsPosts[] = $tag;
280 
281        return $this;
282    }
283 
284    /**
285     * Get tagsPosts
286     *
287     * @return ArrayCollection
288     */
289    public function getTagsPosts() {
290        return $this->tagsPosts;
291    }
292 
293}

Con esto podremos hacer algo así:

1$tags=$post->getTagsPosts();
2foreach($tags as $t){
3      var_dump($t->getTag()->getName());
4}

Y de esta forma sacar de forma muy fácil las tags de un post, sin hacer ningún tipo de join en SQL o con un query builder.

Tendremos que hacer lo mismo con la entidad de usuarios hacia la de posts, para al instanciar un usuario poder sacar todos sus posts.

También debemos hacer la relación OneToMany en la entidad categories para que cuando instanciemos una categoría podamos sacar todos los posts.

Más información:
Relaciones en Doctrine – Documentación oficial

Víctor Robles WEB

Autor: Victor

Desarrollador web - Formador online - Blogger

Compartir este post