|
8 | 8 | use Illuminate\Database\Query\Expression; |
9 | 9 | use Illuminate\Support\Arr; |
10 | 10 | use Illuminate\Support\Collection; |
| 11 | +use Illuminate\Support\LazyCollection; |
11 | 12 | use Illuminate\Support\Str; |
12 | 13 | use Jenssegers\Mongodb\Connection; |
13 | 14 | use MongoCollection; |
14 | 15 | use MongoDB\BSON\Binary; |
15 | 16 | use MongoDB\BSON\ObjectID; |
16 | 17 | use MongoDB\BSON\Regex; |
17 | 18 | use MongoDB\BSON\UTCDateTime; |
| 19 | +use RuntimeException; |
18 | 20 |
|
| 21 | +/** |
| 22 | + * Class Builder |
| 23 | + * @package Jenssegers\Mongodb\Query |
| 24 | + */ |
19 | 25 | class Builder extends BaseBuilder |
20 | 26 | { |
21 | 27 | /** |
@@ -209,12 +215,25 @@ public function get($columns = []) |
209 | 215 | return $this->getFresh($columns); |
210 | 216 | } |
211 | 217 |
|
| 218 | + /** |
| 219 | + * @inheritdoc |
| 220 | + */ |
| 221 | + public function cursor($columns = []) |
| 222 | + { |
| 223 | + $result = $this->getFresh($columns, true); |
| 224 | + if ($result instanceof LazyCollection) { |
| 225 | + return $result; |
| 226 | + } |
| 227 | + throw new RuntimeException("Query not compatible with cursor"); |
| 228 | + } |
| 229 | + |
212 | 230 | /** |
213 | 231 | * Execute the query as a fresh "select" statement. |
214 | 232 | * @param array $columns |
215 | | - * @return array|static[]|Collection |
| 233 | + * @param bool $returnLazy |
| 234 | + * @return array|static[]|Collection|LazyCollection |
216 | 235 | */ |
217 | | - public function getFresh($columns = []) |
| 236 | + public function getFresh($columns = [], $returnLazy = false) |
218 | 237 | { |
219 | 238 | // If no columns have been specified for the select statement, we will set them |
220 | 239 | // here to either the passed columns, or the standard default of retrieving |
@@ -402,6 +421,14 @@ public function getFresh($columns = []) |
402 | 421 | // Execute query and get MongoCursor |
403 | 422 | $cursor = $this->collection->find($wheres, $options); |
404 | 423 |
|
| 424 | + if ($returnLazy) { |
| 425 | + return LazyCollection::make(function () use ($cursor) { |
| 426 | + foreach ($cursor as $item) { |
| 427 | + yield $item; |
| 428 | + } |
| 429 | + }); |
| 430 | + } |
| 431 | + |
405 | 432 | // Return results as an array with numeric keys |
406 | 433 | $results = iterator_to_array($cursor, false); |
407 | 434 | return $this->useCollections ? new Collection($results) : $results; |
|
0 commit comments