Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foreach loops breaks when takes count inside loop #2549

Closed
aanair08 opened this issue Sep 20, 2023 · 3 comments
Closed

foreach loops breaks when takes count inside loop #2549

aanair08 opened this issue Sep 20, 2023 · 3 comments
Labels
Milestone

Comments

@aanair08
Copy link

aanair08 commented Sep 20, 2023

I recently found that when applying foreach loop to the result of an ODM query and taking its count inside the loop, the loop breaks. For example

$query = $dm->createQueryBuilder(Product::class);
$query->field('category.id')->equals($category);
$query->field('stock')->gt(0);
$products = $query->getQuery()->execute();
foreach($products as $product){
   $totalProduct=count($products);
}

This loop executes only one time even if the count of results is more. But when removing count inside loop it works normally.

@alcaeus
Copy link
Member

alcaeus commented Sep 21, 2023

This is somewhat expected due to the way cursors in MongoDB work. In order to count results, we have to exhaust the underlying Cursor, which will cause the current iteration state to be lost. I'd have to check whether it's possible to work around this without a big effort in the ODM, but for the time being you should not run count on results object while you're iterating them. What's preventing you from fetching the count before starting iteration?

@aanair08
Copy link
Author

@alcaeus I have found a workaround for my situation. I just reported the issue to know if is this expected behavior or not. Thank you for your response and time.

@malarzm malarzm added the Bug label Nov 3, 2023
@malarzm malarzm added this to the 2.5.4 milestone Nov 3, 2023
@malarzm
Copy link
Member

malarzm commented Nov 3, 2023

Fixed in #2570

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants