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

Ite*_*tor 3 php doctrine symfony doctrine-orm

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

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

$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;
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ark 5

您将必须重构您的实体以引入新的实体并将user_notifications邻接表转换为实体。

解决方案

按如下方式转换表:在此输入图像描述

然后重构您的关联,如下所示:

用户实体

...
/**
 * @OneToMany(targetEntity="UserNotification", mappedBy="notification_id")
 **/
private $notifications;
Run Code Online (Sandbox Code Playgroud)

通知实体

...
/**
 * @OneToMany(targetEntity="UserNotification", mappedBy="user_id")
 **/
private $users;
Run Code Online (Sandbox Code Playgroud)

用户通知实体

/** @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;
Run Code Online (Sandbox Code Playgroud)