我想创建一个通知系统。有一个 Notification
类。通知可以分配给多个用户,而不仅仅是一个。
有一个联合表user_notifications
,有两列:user_id
和notification_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
邻接表转换为一个实体。
解决方案
按如下方式转换表格:
然后按如下方式重构您的关联:
用户实体
...
/**
* @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/