如何在 Doctrine2 中向连接 table 添加额外的列?

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

我想创建一个通知系统。有一个Notificationclass。一个通知可以分配给多个用户,而不仅仅是一个。

有一个联合 table user_notifications,有两列:user_idnotification_id

用户class中$notifications的定义是这样的:

/**
 * @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;

一切正常。但是我想在 user_notifications table 中添加一个新列,我想在其中存储通知是否被给定用户读取。我应该如何在 Doctrine2 中管理它?

您需要使用这个额外的列创建新实体。

您可以在这个答案中找到详细信息:

您将不得不重构您的实体以引入一个新实体并将您的 user_notifications 邻接 table 转换为一个实体。

解决方案

改造你table如下:

然后按如下方式重构您的关联:

用户实体

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

通知实体

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

UserNotification 实体

/** @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;