Yohann
Yohann

Reputation: 275

Doctrine2 ManyToMany with additional attribute

I used to manipulate databases, I would like to create under Symfony2/Doctrine2 a ManyToMany model with attribute createdAt, for a model about favorite posts.

Here is my current code

A User Entity with :

/**
* @ORM\ManyToMany(targetEntity="App\Entity\Post", inversedBy="posts", cascade={"persist"})
* @ORM\JoinTable(name="favorite")
*/
private $favorites;

and a Post Entity with :

/**
* @ORM\ManyToMany(targetEntity="App\Entity\User", mappedBy="favorites")
*/
private $users;

I have a table favorite(post_id, user_id) which is created.

How can I create a table favorite(post_id, user_id, createdAt) ?

Thanks

Upvotes: 2

Views: 4851

Answers (1)

René
René

Reputation: 672

You would do this by creating an one-to-many-to-one relationship and creating your own entity in the middle

In the User entity:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\UserFavorites", mappedBy="user", cascade={"persist"})
 */
private $userFavorites;

Do the same for Post entity:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\UserFavorites", mappedBy="post", cascade={"persist"})
 */
private $userFavorites;

create a UserFavorites entity to connect the 2:

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="userFavorites")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
private $user;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Post", inversedBy="userFavorites")
 * @ORM\JoinColumn(name="post_id", referencedColumnName="id")
 */
private $post;

/**
 * @var datetime $created
 *
 * @ORM\Column(name="created", type="datetime")
 */
private $created;

Upvotes: 14

Related Questions