Symfony2 and the Doctrine of ManyToMany realtionship

I raise a headache about it, and I do not find a solution.

I have 2 objects: Movie.php and Category.php

I want one movie to have several categories and vice versa. This is why I chose ManyToMany relationships.

Now I'm wondering ... What is happening on the database site? Is there a "staging" table that displays movie_ids in category_ids? But that is not what happened. In fact, my first attempt was to create a MovieCategory object - I matched one movie with several categories to OneToMany, and in essence MovieCategory I made a one-way join to get the category name from my category. But I think that is not how it should work, right?

Now here is my code of how I think it should work, I really appreciate any help I can get about this:

Movie.php

<?php /** * @ORM\Table(name="movies") * @ORM\HasLifecycleCallbacks() */ class Movie { public function __construct() { $this->categories = new ArrayCollection(); } /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** @ORM\Column(type="string") */ protected $moviename; /** * @ORM\ManyToMany(targetEntity="Category", mappedBy="movie") */ protected $categories; } 

category.php

 <?php /** * @ORM\Table(name="categories") * @ORM\HasLifecycleCallbacks() */ class Category { public function __construct() { $this->movies = new ArrayCollection(); } /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string") */ protected $name; // ... /** * @ORM\ManyToMany(targetEntity="Movie", mappedBy="movie", cascade={"persist"}) */ protected $movies; } 
+4
source share
2 answers

According to the Doctrine docs , it should look like this:

 // Movie.php /** * @ORM\ManyToMany(targetEntity="Category", inversedBy="movies") * @ORM\JoinTable(name="movies_categories") */ protected $categories; // ... // Category.php /** * @ORM\ManyToMany(targetEntity="Movie", mappedBy="categories") */ protected $movies; 
+12
source

You use the same value for mappedBy in both ads. In addition, the value you use is exceptional, it must be plural. This will not work.

0
source

Source: https://habr.com/ru/post/1395779/


All Articles