如何在Doctrine 2.0中编写UNION

时间:2010-11-11 14:19:23

标签: 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

4 个答案:

答案 0 :(得分:13)

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

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

然后扩展通知的两个类( NotificationGroup NotificationEvent ):

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

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

答案 1 :(得分: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

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

答案 2 :(得分:1)

Doctrine,s不支持

UNION。讨论here

答案 3 :(得分:1)

$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();