1

In my symfony aplication, I recover a variable as a string by my ajax script.

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.

How can I make a query with an array of parameter or make a foreach in doctrine query builder ?

I have already try something this in a queryBuilder method:

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

it returns me an error : SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s)

I try this too in the 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.

1

3 Answers 3

1

If you want to check if the id is within a certain set of given ids you can use IN.

$qb = $this->createQueryBuilder('s')
        ->addSelect('u')
        ->innerJoin('s.field','u')
        ->where("u.id IN(:ids)")
        ->setParameter('ids', array_values($ids));
Sign up to request clarification or add additional context in comments.

Comments

0

Try using the ->setParameter('ids', $ids). where $ids is the array of ids

2 Comments

see my edit, in fact if I use setParameters("ids" => $ids) I have an error of SQLState for the cardinality like SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s). As it is wrote, the dql does not accept an array here.
->where('topic.user IN (:userIds)') ->setParameter('userIds', $userIds);
0

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

array contains many values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.