Doctrine DBAL - WHERE IN array with additional parameter
Asked Answered
U

2

32

Using the example docs, I was able to get a query like this to work.

SELECT
f.foo,
b.bar
FROM Foo f
LEFT JOIN Bar b
WHERE 
f.foo = 20
AND b.bar IN ?

Using DBAL, this code returns results.

$result = $this->connection->executeQuery(
            $SQL,
            array($bar_array),
            array(\Doctrine\DBAL\Connection::PARAM_INT_ARRAY)
        )->fetchAll();

I would like to search for f.foo as a single integer parameter well as looking for the IN statement, but I haven't figured out how to get it to function, since all of the example documents have the array as the only parameter.

Undesigning answered 8/5, 2014 at 18:25 Comment(0)
M
41

The params and types are parallel arrays. All you should have to do is add your placeholder for the f.foo value and add in the correct PDO type in types argument.

$SQL = "SELECT f.foo, b.bar
        FROM Foo f LEFT JOIN Bar b
        WHERE  f.foo = ? AND b.bar IN (?)";

$result = $this->connection
    ->executeQuery($SQL, array($foo, $bar_array),array(
            \PDO::PARAM_INT,
            \Doctrine\DBAL\ArrayParameterType::INTEGER
     ))->fetchAll();

You can read the manual for more information.

Mariann answered 8/5, 2014 at 18:31 Comment(1)
If you read this around 2024, replace \Doctrine\DBAL\Connection::PARAM_INT_ARRAY with \Doctrine\DBAL\ArrayParameterType::INTEGER. At least that's how it works in doctrine/dbal:3.7.1, but I didn't check in which version exactly they changed it.Cobweb
S
32

I just encountered the below behavior, so I am writing it here, maybe it will prove useful for someone else.

Beware when using named parameters with IN. You will have to repeat the names for the type-array as well:

$sql = "SELECT * FROM myTable WHERE name IN (:param_array)";

$stmt = $this->db->executeQuery(
        $sql,
        [
            'param_array' => $paramArray
        ],
        [
            'param_array' => Connection::PARAM_STR_ARRAY
        ]
    );
Septempartite answered 19/4, 2016 at 7:4 Comment(2)
The above thankfully works fine now, since at least DBAL 2.6 (possibly earlier)Sedgewick
Thanx, man! I spend 3 hours trying to achieve this. whit no success.Thickleaf

© 2022 - 2024 — McMap. All rights reserved.