Skip to content

Commit

Permalink
Support column aliases in chunkById
Browse files Browse the repository at this point in the history
References #14499
  • Loading branch information
mzur committed Aug 9, 2016
1 parent 3b91351 commit dad8ca6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1783,20 +1783,23 @@ public function chunk($count, callable $callback)
* @param int $count
* @param callable $callback
* @param string $column
* @param string $alias Alias of the ID column if there are multiple columns with the same name. The alias must be defined in a select statement.
* @return bool
*/
public function chunkById($count, callable $callback, $column = 'id')
public function chunkById($count, callable $callback, $column = 'id', $alias = null)
{
$lastId = null;

$alias = is_null($alias) ? $column : $alias;

$results = $this->forPageAfterId($count, 0, $column)->get();

while (! empty($results)) {
if (call_user_func($callback, $results) === false) {
return false;
}

$lastId = last($results)->{$column};
$lastId = last($results)->{$alias};

$results = $this->forPageAfterId($count, $lastId, $column)->get();
}
Expand Down
13 changes: 13 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1667,6 +1667,19 @@ public function testChunkPaginatesUsingId()
}, 'someIdField');
}

public function testChunkPaginatesUsingIdWithAlias()
{
$builder = $this->getMockQueryBuilder();
$builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'table.id')->andReturn($builder);
$builder->shouldReceive('forPageAfterId')->once()->with(2, 10, 'table.id')->andReturn($builder);
$builder->shouldReceive('get')->times(2)->andReturn(
[(object) ['table_id' => 1], (object) ['table_id' => 10]],
[]
);
$builder->chunkById(2, function ($results) {
}, 'table.id', 'table_id');
}

public function testPaginate()
{
$perPage = 16;
Expand Down

0 comments on commit dad8ca6

Please sign in to comment.