简体   繁体   English

参数dql / queryBuilder,带有foreach或参数数组

[英]doctrine dql/queryBuilder with a foreach or array in parameters

In my symfony aplication, I recover a variable as a string by my ajax script. 在我的symfony应用中,我通过ajax脚本将变量恢复为字符串。

This variable looks like this: 该变量如下所示:

$slug = "1-2-3-4-4-5-6-7" /* it could more*/
$vars = explode('-',$slug ); /*push the $slug string in an array */

/* recover all value of the array */
foreach ($vars as $var) {
      echo $var;
    }

Now I need to use this foreach in a dql or a query builder because all $var are ids of an entity and i need to pass all this value to get the right result. 现在,我需要在dqlquery builder使用此foreach,因为所有$ var都是实体的ID,并且我需要传递所有这些值以获得正确的结果。

How can I make a query with an array of parameter or make a foreach in doctrine query builder ? 如何在参数查询构建器中使用参数数组进行查询或进行foreach?

I have already try something this in a queryBuilder method: 我已经在queryBuilder方法中尝试了以下方法:

->setParameters("id" => $vars);

it returns me an error : SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s) 它返回一个错误: SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)

I try this too in the queryBuilder: 我也尝试在queryBuilder中这样做:

->setParameters(array('id' => array($vars)));

Here I have no error, but it does not return the good result. 在这里,我没有错误,但是没有返回好的结果。 Indeed I have only one result in database if there are many ids. 确实,如果有许多ID,数据库中只有一个结果。

If you want to check if the id is within a certain set of given ids you can use IN . 如果要检查ID是否在给定ID的特定集合内,则可以使用IN

$qb = $this->createQueryBuilder('s')
        ->addSelect('u')
        ->innerJoin('s.field','u')
        ->where("u.id IN(:ids)")
        ->setParameter('ids', array_values($ids));

Try using the ->setParameter('ids', $ids). 尝试使用-> setParameter('ids',$ ids)。 where $ids is the array of ids $ ids是id的数组

The solution is here . 解决方案在这里

I created a more complex query in order to answer to all condition: 我创建了一个更复杂的查询以回答所有情况:

array is empty 数组为空

array contains only 1 value 数组仅包含1个值

array contains many values 数组包含许多值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM