Laravel MySQL的闭包不像预期的那样工作


Laravel MySQL whereIn Closure Not Working As Expected

谁能帮助解释为什么下面的一个Laravel查询工作,而另一个没有?

第一个成功的:

$array = ( 1, 2, 3 ,4 );
$query->whereIn( 'status_id', $array );

按预期工作。但是,当我尝试传递一个函数来构建数组时:

$query->whereIn( 'status_id', function() use ( $statuses ){
    $status_array = array();
    foreach( $statuses as $status ){
         $status_array[] = $status->status_id;
    }
    return $status_array;
});

我得到以下错误:

一般错误:1096 No tables used (SQL: select * from jobs where .status_id in (select *))

我已经检查了我在闭包中构建的数组与工作的数组相同,并且它是。我是否错过了一些关于where()和它的闭包函数的基本内容?我甚至可以将闭包传递给where()吗?

当你在whereIn()中使用闭包时,Laravel会认为你将做一个子查询。因此,在错误消息中,您可以在in中看到另一个select

在传递给whereIn()

之前,您需要解析您的值数组。
foreach ($statuses as $status) {
     $status_array[] = $status->status_id;
}
$query->whereIn('status_id', $status_array);

Extra:参见Laravel源码。

照亮' '数据库查询'建设者:

public function whereIn($column, $values, $boolean = 'and', $not = false)
{
    ...
    if ($values instanceof Closure)
    {
        return $this->whereInSub($column, $values, $boolean, $not);
    }
}

调用whereInSub():

protected function whereInSub($column, Closure $callback, $boolean, $not)
{
    $type = $not ? 'NotInSub' : 'InSub';
    // To create the exists sub-select, we will actually create a query and call the
    // provided callback with the query so the developer may set any of the query
    // conditions they want for the in clause, then we'll put it in this array.
    call_user_func($callback, $query = $this->newQuery());
    $this->wheres[] = compact('type', 'column', 'query', 'boolean');
    $this->mergeBindings($query);
    return $this;
}

作为一个相关的答案,而不是运行循环来生成您的列表-只需让Laravel为您做

 $status_array= DB::table('status')->lists('status_id');

然后使用

 $query->whereIn( 'status_id', $status_array );

我想你的函数返回一个像这样的数组:

[ 0 => status_id_value_0,
  1 => status_id_value_1, 
  ...
] 

尝试返回一个array_values($status_array)来检查它。

无论如何,试试这个:

$query->whereIn( 'status_id', 
                 array_values(
                     array_map(
                         function($pos){return $pos->status_id;},
                         $statuses
                     )
                 )
               ); 

我希望它对你有用。

在传递给where之前需要将逗号分隔的值转换为数组。

,这也适用于任何动态内容

    foreach ($statuses as $status) {
         $status_array[] = $status->status_id;
    }
    $query->whereIn('status_id', $status_array);