如何从闭包中终止 Eloquent 分块
How to terminate Eloquent chunking from closure
如何使用 Eloquent,根据 chunk
函数闭包中的条件终止分块?我试过返回,但这似乎只终止当前块而不是所有块。此时,我想停止从数据库中检索记录。
$query->chunk(self::CHUNK_SIZE, function ($objects) {
if (someCondition) {
// terminate chunking here
return;
}
});
如果你 return false
它会崩溃。
如果你在 do while
循环和 return
任何它会退出循环。在下面的源代码中你可以看到:
if ($callback($results) === false) {
return false;
}
这给了你退出的机会。
/**
* Chunk the results of the query.
*
* @param int $count
* @param callable $callback
* @return bool
*/
public function chunk($count, callable $callback)
{
$this->enforceOrderBy();
$page = 1;
do {
// We'll execute the query for the given page and get the results. If there are
// no results we can just break and return from here. When there are results
// we will call the callback with the current chunk of these results here.
$results = $this->forPage($page, $count)->get();
$countResults = $results->count();
if ($countResults == 0) {
break;
}
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if ($callback($results) === false) {
return false;
}
$page++;
} while ($countResults == $count);
return true;
}
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Concerns/BuildsQueries.php#L18
如何使用 Eloquent,根据 chunk
函数闭包中的条件终止分块?我试过返回,但这似乎只终止当前块而不是所有块。此时,我想停止从数据库中检索记录。
$query->chunk(self::CHUNK_SIZE, function ($objects) {
if (someCondition) {
// terminate chunking here
return;
}
});
如果你 return false
它会崩溃。
如果你在 do while
循环和 return
任何它会退出循环。在下面的源代码中你可以看到:
if ($callback($results) === false) {
return false;
}
这给了你退出的机会。
/**
* Chunk the results of the query.
*
* @param int $count
* @param callable $callback
* @return bool
*/
public function chunk($count, callable $callback)
{
$this->enforceOrderBy();
$page = 1;
do {
// We'll execute the query for the given page and get the results. If there are
// no results we can just break and return from here. When there are results
// we will call the callback with the current chunk of these results here.
$results = $this->forPage($page, $count)->get();
$countResults = $results->count();
if ($countResults == 0) {
break;
}
// On each chunk result set, we will pass them to the callback and then let the
// developer take care of everything within the callback, which allows us to
// keep the memory low for spinning through large result sets for working.
if ($callback($results) === false) {
return false;
}
$page++;
} while ($countResults == $count);
return true;
}
https://github.com/laravel/framework/blob/5.4/src/Illuminate/Database/Concerns/BuildsQueries.php#L18