17

如何在 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
4

4 回答 4

14

好吧,我发现也许是最好的解决方案:

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

然后两个类(NotificationGroupNotificationEvent)扩展Notification

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

/**
 * @Entity
 */
class NotificationEvent extends Notification {
    //...
}
于 2010-11-11T15:30:42.667 回答
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

视图将是另一个很好的解决方案,但是它是否也支持写入操作取决于您的数据库供应商。

于 2010-11-16T12:45:51.397 回答
2

UNIONDoctrine, s 不支持。这里的讨论。

于 2010-11-11T14:22:10.480 回答
2
$connection = $em->getConnection();
$query = $connection->prepare("SELECT field1, field2 FROM table1 
                                UNION
                                SELECT field3, field4 FROM table2 
                                UNION 
                                SELECT field5, field6 FROM table3
                                ");
$query->execute();
$result = $query->fetchAll();
于 2016-06-29T11:59:52.433 回答