php - 如何向 Doctrine2 中的连接表添加额外的列?

标签 php symfony doctrine-orm doctrine

我想创建一个通知系统。有一个 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;

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

最佳答案

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

解决方案

按如下方式转换表格:enter image description here

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

用户实体

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

关于php - 如何向 Doctrine2 中的连接表添加额外的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31481126/

相关文章:

php - 德鲁帕尔 6 : Make custom function available to different modules

php - 为什么不反斜杠每个空格以防止 mysql 注入(inject)

php - Docker:创建一个完全安装的PHP应用程序

php - 合并来自两个不同 MySql 查询的两个不同数组

validation - symfony2 2.3 缺少FormBuilder::addValidator() 如何适配FormBuilderInterface?

unit-testing - 使用 PHPUnit 测试用例断言 403 Access Denied http 状态

symfony - Doctrine2 - 保留具有关联的实体而不获取关联实体

mysql - 提高大型 Doctrine 查询的性能

Symfony 教义 : join a table with a view after persisting entity

mysql - Doctrine 忽略数据库的字符集和排序规则