I was trying to a run raw sql query with doctrine entitymanager for IN clause as shown below.
$idSArray = Array ( [0] => 1 [1] => 2 )
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)');
$params = array(
'ids' => implode( ",", $idSArray )
);
$stmt->execute($params);
$results = $stmt->fetchAll();
But I am only getting result for Id = 1. If I hardcode the WHERE IN condition as
WHERE t1.id = t2.matchId AND t1.id IN (1,2)');
Then getting result for both the Ids. Can anyone tell me that what I am doing wrong in passing the $params array. I have also print the implode result which outputs 1,2. So I am not able to find the mistake and also the way to perform raw sql query with IN clause.
Answer:
So there are at least two mistakes you did. The first is what @Alarid said: you should not implode your array. The second is that you have to use DoctrineDBALTypes Conversion
for IN clause
when running a prepared statement.
And finally your query goes this:
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->prepare('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)');
$stmt->bindValue('ids', $idSArray, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
$stmt->execute();
Or alternative:
$stmt = $this->getDoctrine()->getEntityManager()
->getConnection()
->executeQuery('SELECT t1.id , t1.name , t2.start_date , t2.end_date
FROM table1 t1 , table2 t2
WHERE t1.id = t2.matchId AND t1.id IN (:ids)',
array('ids' => $idSArray),
array('ids' => \Doctrine\DBAL\Connection::PARAM_INT_ARRAY)
)
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With