【问题标题】:How to add additional columns to a join table in Doctrine2?如何在 Doctrine2 的连接表中添加额外的列?
【发布时间】:2015-10-07 11:42:30
【问题描述】:

我想创建一个通知系统。有一个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 中管理它?

【问题讨论】:

    标签: php symfony doctrine-orm doctrine


    【解决方案1】:

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

    您可以在此答案中找到详细信息:https://stackoverflow.com/a/15630665/1348344

    【讨论】:

      【解决方案2】:

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

      解决方案

      按如下方式转换您的表格:

      然后重构你的关联如下:

      用户实体

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

      通知实体

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

      用户通知实体

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

      【讨论】:

        猜你喜欢
        • 2021-10-29
        • 2013-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-15
        • 1970-01-01
        • 2020-03-18
        • 2019-11-12
        相关资源
        最近更新 更多