Cakephp3将数组传递给where条件

时间:2016-04-26 10:56:21

标签: cakephp cakephp-3.0

我正在处理这段代码:

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();
}

代码几乎是自我解释,我想更新所有具有id的行,这些行将在数组中传递给函数。

我通过这样做测试了代码:

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

它的工作正常,但我不能将传递的数组参数传递给where where条件,因为它给出了语法错误未声明的变量$ array。

关于如何实现这一点的任何想法都会很棒。

1 个答案:

答案 0 :(得分:3)

您可以使用use语言构造将外部变量包含到匿名函数

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

但你可以做到

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

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

请参阅manual

相关问题