Wildchild
Wildchild

Reputation: 243

Native SQL in Doctrine: set types of multiple query parameters

I'm using NativeSQL and I need to set an undefined number of parameters. My code:

$entityManager = $this->getEntityManager();
$rsm = new Query\ResultSetMappingBuilder($entityManager);
$mySql = "
   SELECT *
   FROM table1 t1
   INNER JOIN table2  t2 ON t2.t1_id = t1.id
   ...
   WHERE t1.name = :t1_name AND t2.age = :t2_age AND ...
";
// array of multiple query parameters (name, value)
$queryParameters = array(
   't1_name' => 'Andy',
   't2_age' => 12,
   ...
);
$query = $entityManager->createNativeQuery($mySql, $rsm);
$query->setParameters($queryParameters);
$salidas = $query->getResult();

I need to set the type of every query parameters but setParameters() function doesn't allow pass this types.

I see that setParameter() function of AbstractQuery (Doctrine class) allow pass this types, but I would like to use setParamaters() function because I have to pass an undefined number of paramaters...

How can I solve this? Thanks.

Upvotes: 1

Views: 5485

Answers (1)

Łukasz D. Tulikowski
Łukasz D. Tulikowski

Reputation: 1503

You can pass multiple parameters to your query using the following:

$entityManager = $this->getEntityManager();

$sql = "
   SELECT *
   FROM table1 t1
   INNER JOIN table2  t2 ON t2.t1_id = t1.id
   ...
   WHERE t1.name = :t1_name AND t2.age = :t2_age AND ...
";

// array of multiple query parameters (name, value)
$stmt = $entityManager->getConnection()->prepare($sql);

$stmt->execute([
    't1_name' => 'Andy',
     t2_age' => 12,
    ...
]);

$results = $stmt->fetchAll();

Reference Data Retrieval And Manipulation

Upvotes: 2

Related Questions