如何在Doctrine 2.0中编写UNION

Išk*_*uda 14 sql union doctrine-orm

如何在Doctrine 2.0中编写这个SQL查询(并获取结果)?

(SELECT 'group' AS type, 
    CONCAT(u.firstname, " ", u.surname) as fullname, 
    g.name AS subject,
    user_id, 
    who_id, 
    group_id AS subject_id,
    created 
  FROM group_notification 
  JOIN users u ON(who_id = u.id) 
  JOIN groups g ON(group_id = g.id)
)

   UNION 

(SELECT 'event' AS type, 
    CONCAT(u.firstname, " ", u.surname) as fullname, 
    e.name AS subject, 
    user_id, 
    who_id, 
    event_id AS subject_id, 
    created 
  FROM event_notification 
  JOIN users u ON(who_id = u.id) 
  JOIN events e ON(event_id = e.id)
)
   ORDER BY created
Run Code Online (Sandbox Code Playgroud)

Išk*_*uda 13

好吧,我发现可能是最好的解决方案:

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"group" = "NotificationGroup", "event" = "NotificationEvent"})
 */
class Notification {
   // ...
}
Run Code Online (Sandbox Code Playgroud)

然后两个类(NotificationGroupNotificationEvent)扩展通知:

/**
 * @Entity
 */
class NotificationGroup extends Notification {
    //...
}

/**
 * @Entity
 */
class NotificationEvent extends Notification {
    //...
}
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案的解释如何? (15认同)

beb*_*lei 11

DQL不支持UNION,但您仍然可以编写UNION查询并使用本机查询功能来检索数据:

http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html

但是,根据您的示例,您似乎希望每个类继承使用某种形式的表,但尚不支持.如果可以更改模式,还有另一种形式的继承(加入表继承).

http://www.doctrine-project.org/projects/orm/2.0/docs/reference/inheritance-mapping/en#class-table-inheritance

一个视图将是另一个好的解决方案,但是如果它也支持写操作,则它取决于您的数据库供应商.

  • 链接坏了,这里是好的:http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html (3认同)