Iter Ator
Iter Ator

Reputation: 9324

How to add additional columns to a join table in Doctrine2?

I would like to create a notification system. There is a Notification class. A notification can be assigned to more than one users, not just one.

There is a joint table user_notifications, with two columns: user_id and notification_id

The definition of the $notifications in the user class is this:

/**
 * @ManyToMany(targetEntity="Notification")
 * @JoinTable(name="user_notifications",
 *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@JoinColumn(name="notification_id", referencedColumnName="id", unique=true)}
 *      )
 **/
private $notifications;

Everything works fine. But I would like to add a new column to the user_notifications table, where I would like to store, if the notification is read by the given user, or not. How should I manage it in Doctrine2?

Upvotes: 4

Views: 1926

Answers (2)

Mark
Mark

Reputation: 5787

You will have to refactor your entities to introduce a new and transform your user_notifications adjacency table into an entity.

Solution

Transform you table as follows: enter image description here

Then refactor your associations as follows:

User entity

...
/**
 * @OneToMany(targetEntity="UserNotification", mappedBy="notification_id")
 **/
private $notifications;

Notification entity

...
/**
 * @OneToMany(targetEntity="UserNotification", mappedBy="user_id")
 **/
private $users;

UserNotification entity

/** @Entity **/
class UserNotification {
...
/**
 * @ManyToOne(targetEntity="User", inversedBy="notifications")
 * @JoinColumn(name="user_id", referencedColumnName="id")
 **/
private $user_id;

/**
 * @ManyToOne(targetEntity="Notification", inversedBy="users")
 * @JoinColumn(name="notification_id", referencedColumnName="id")
 **/
private $notification_id;

/** @Column(type="boolean") */
private $read;

Upvotes: 5

Tomas Votruba
Tomas Votruba

Reputation: 24298

You'll need to create new entity with this extra column.

You can find details in this answer: https://stackoverflow.com/a/15630665/1348344

Upvotes: 2

Related Questions