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;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With