Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with UNION in Doctrine Symfony

I have a question about the translation of a SQL query in Doctrine Symfony. I would like to do a thing like that :

SELECT m.*
FROM member m
INNER JOIN (
  SELECT id_member
  FROM friend
  WHERE id_friend=99
  UNION
  SELECT id_friend
  FROM friend
  WHERE id_member=99
) a ON m.id=a.id_member 
WHERE m.visible=1

In this example, i search all friends of the user 99.

My tables :

Member: (id, name, visible)
Friend: (id, id_member, id_friend, active)

Precision : I would like to use the Symfony pager.

A solution ? Thank you !

like image 696
Hofstadter Avatar asked Nov 02 '11 13:11

Hofstadter


People also ask

Can we use union in SELECT query?

The UNION operator is used to combine the data from the result of two or more SELECT command queries into a single distinct result set. This operator removes any duplicates present in the results being combined.

Does Symfony use Doctrine?

Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.

Can we use union in view?

The SQL UNION command allows you to display records from two different tables or queries as though they were in one table. The UNION Command can only be used in SQL Direct mode. Views are similar to Queries, but with several differences: Not all database connections allow for Views.


2 Answers

UNION is not supported within DQL, but you can issue your query using RAW SQL ->

$q = Doctrine_Manager::getInstance()->getCurrentConnection();
$result = $q->execute(" -- RAW SQL HERE -- ");
like image 192
Manse Avatar answered Oct 24 '22 10:10

Manse


Other alternative to @ManseUK is:

$em = $this->getEntityManager();
$connection = $em->getConnection();
$statement = $connection->prepare("-- RAW SQL HERE --");
$statement->execute();

return $statement->fetchAll();
like image 3
iarroyo Avatar answered Oct 24 '22 08:10

iarroyo