2010-11-11 55 views
13

如何在Doctrine 2.0中編寫這個SQL查詢(並獲取結果)?如何在Doctrine 2.0中編寫UNION

(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 

回答

13

嗯,我發現也許是最好的解決辦法:

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

然後兩班(NotificationGroupNotificationEvent)延伸通知:在不支持

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

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

該解決方案的解釋如何? – ihsan 2014-12-25 01:04:42

+0

@ihsan你可以從基類庫('Notification')中選擇,並且你可以得到子類型的所有對象('NotificationGroup','NotificationEvent',甚至只是'Notification',如果你還沒有聲明它是抽象的)。如果你只需要某些類型,那麼你可以在WHERE中使用'INSTANCE OF'運​​算符。 – 2016-02-04 12:44:43

1

UNION在Doctrine,s中不受支持。討論here

+0

是的,我知道。是否有任何解決方法,要做到這一點? – 2010-11-11 14:23:24

+1

作爲一箇中間解決方案,您可以使用VIEW來獲得UNION支持。 – 2010-11-11 14:24:28

11

UNION DQL,但仍然可以編寫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

視圖將是另一個很好的解決方案,但後來它取決於你的數據庫供應商,如果它也支持寫入操作與否。

+3

鏈接中斷,這裏是好的:http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html – 2014-02-26 11:53:45

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(); 
相關問題