Iškuda
Iškuda

Reputation: 645

How to write UNION in Doctrine 2.0

How to write this SQL query in Doctrine 2.0 (and fetch results)?

(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

Upvotes: 20

Views: 53954

Answers (4)

beberlei
beberlei

Reputation: 4337

UNION is not supported in DQL, but you can still write a UNION query and use the Native Query capabilities to retrieve the data:

https://www.doctrine-project.org/projects/doctrine-orm/en/2.16/reference/native-sql.html#native-sql

However from your example it seems you want to use some form of table per class inheritance, which is not yet supported. There is another form of inheritance, (Joined Table Inheritance) that works though, if you can change your schema.

https://www.doctrine-project.org/projects/doctrine-orm/en/2.16/reference/inheritance-mapping.html#class-table-inheritance

A view would be another good solution, but then it depends on your database vendor if it also supports write operations or not.

Upvotes: 12

Haim Evgi
Haim Evgi

Reputation: 125564

UNION is not supported in Doctrine, s. the discussion here.

Upvotes: 3

Milan Vidovic
Milan Vidovic

Reputation: 69

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

Upvotes: 2

Iškuda
Iškuda

Reputation: 645

Well, I found maybe the best solution:

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

And then two classes (NotificationGroup and NotificationEvent) extending Notification:

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

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

Upvotes: 14

Related Questions