Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 and Doctrine ManyToMany realtionship

I am heaving some headache about this and I don't find the solution.

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

I want one Movie to have multiple Categories and vice versa. That's why I chose a ManyToMany relationship.

Now I am wondering... What happens on the database site? Is there a "in-between" table that maps movie_ids to category_ids? But that's not what happened. Actually my first try was to make a MovieCategory entity - I mapped one movie to multiple categories with OneToMany and in the MovieCategory entity I made a OneToOne connection to get the category name from my Category entity. But I guess that's not how it should work, am I right?

Now here's my code of how i think it should work, I really appreciate any help I can get on 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;


}
like image 703
Mike Avatar asked Dec 16 '22 04:12

Mike


1 Answers

According to Doctrine docs it should look this way:

// 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;
like image 96
Molecular Man Avatar answered Jan 07 '23 10:01

Molecular Man