Last active
February 3, 2017 19:31
-
-
Save alairock/12b3d2f749acce53ef7ab919a069fe4c to your computer and use it in GitHub Desktop.
Using a Generator in PHP. Helpful when you need to work on hundreds....thousands....millions of records. Don't load them all into memory all at once. Work on them one at a time!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$usersQuery = \App\User::query(); | |
$usersQuery->where('type', '=', 'client'); | |
foreach(generate($usersQuery) as $user) { | |
// Do something with that user | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function generate($query) { | |
$sql = $query->toSql(); | |
$bindings = $query->getBindings(); | |
$pdo = \DB::connection()->getPdo(); | |
$stmt = $pdo->prepare($sql); | |
$stmt->execute($bindings); | |
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { | |
yield $row; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment