我有一个我可能想在我的数据库中寻找的字段数组:
$locations = array(
2,3,5
);
位置数量可能不同,我想创建一个准备好的语句(在Symfony2中使用Doctrine),它与此相同:
SELECT * FROM locations WHERE start = 1 AND (end = 2 OR end = 3 OR end = 5)
(我认为)我知道如何使用预习语句,如下所示:
$query = $em->createQuery(
'SELECT l
FROM AppBundle:Location l
WHERE l.start > :start
AND (l.end = :end1
OR l.end = :end2
OR l.end = :end3)
ORDER BY l.duration ASC'
)
->setParameter('start', '1')
->setParameter('end1', '2')
->setParameter('end2', '3')
->setParameter('end3', '5');
但是如果我没有数组的大小,我怎么能动态地做呢?
任何暗示都赞赏!
答案 0 :(得分:2)
<?php
$locations = array(
2,3,5
);
$query = $em->createQuery(
'SELECT l
FROM AppBundle:Location l
WHERE l.start > :start
AND l.end IN :end
ORDER BY l.duration ASC'
)
->setParameter('start', '1');
->setParameter('end', $locations);
?>
答案 1 :(得分:1)
@Christian的答案很好,但只是为了完成,您可以使用foreach
来创建SQL字符串。
<?php
$locations = array(2, 3, 5);
$endQueries = [];
foreach ($locations as $i => $location) {
$endQueries[] = "l.end = :end{$i}";
}
$queryString = 'SELECT l
FROM AppBundle:Location l
WHERE l.start > :start
AND (' . implode(' OR ', $endQueries) . ')
ORDER BY l.duration ASC';
$query = $em->createQuery($queryString);
$query->setParameter("start", '1');
foreach ($locations as $i => $location) {
$query->setParameter("end{$i}", $location);
}
答案 2 :(得分:0)
也许你错过了fetchAll?
<?php
$locations = array(
2,3,5
);
$query = $em->createQuery(
'SELECT l
FROM AppBundle:Location l
WHERE l.start > :start
AND l.end IN :end
ORDER BY l.duration ASC'
)
->setParameter('start', '1');
->setParameter('end', $locations);
/* == Added a fetchAll call == */
$query->execute->fetchAll();
?>