使用查询函数会出现错误


Laravel - Using query function gives an error

我试图采取$max的结果。但有时$max为NULL,因此查询必须返回所有结果。

我使用以下代码:

$results = MyModel::whereIn('player', $players)->take(function($query) use ($max) {
    if (isset($max)) {
        $query->take($max);
    }
})->get();

但是我得到这个错误:

[ErrorException]                                       
  Object of class Closure could not be converted to int 

你可以试试:

$query = MyModel::whereIn('player', $players);
if (!empty($max)) {
    $query->take($max);
}
$result = $query->get();