1

I'm working on this piece of code:

public function validateSelected($array = [1, 2])
{
    $this->autoRender = false;
    $samples = TableRegistry::get('Samples');
    $samples->query()
        ->update()
        ->set(['validate' => true])
        ->where(function ($exp, $q) {
            return $exp->in('id', $q);
        })
        ->execute();
}

The code is pretty much self explanatory, I want to update all the rows with id's that would be passed in an array to the function.

I've tested the code by doing this:

->where(function ($exp, $q) {
            return $exp->in('id', [1, 2, 3]);
        })

And its working fine but i cant pass the passed array parameter to this where condition as it gives a syntax error undeclared variable $array.

Any idea about how can i achieve this thing would be great.

1 Answer 1

4

you can use the use language construct to include external variables into the anonymous function

 $ids = [1, 2, 3];
 ->where(function ($exp, $q) use($ids) {
        return $exp->in('id', $ids ]);
    })

but you can simply do

->where(['id IN'  => $ids])

or also

->where(['id' => $ids], ['id' => 'integer[]'])

see the manual

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks alot that worked. Can you please explain the purpose of the second parameter in the unknown function?
I guess it's because sometimes you need to access some $query methods inside the anonymous function. See this paragraph for an example
Thanks for the response.

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.