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

PHPORM-238 Add support for withCount and other aggregations #3182

Draft
wants to merge 4 commits into
base: 5.x
Choose a base branch
from

Conversation

GromNaN
Copy link
Member

@GromNaN GromNaN commented Oct 17, 2024

Fix PHPORM-238

Implement this feature from Laravel: https://laravel.com/docs/11.x/eloquent-relationships#counting-related-models
Counting relations with SQL is done using a subquery. For MongoDB, there is 2 ways:

  1. Making a query during eager loading, that count the objects for each result ID. This is an aggregation with a $group by foreign key.
  2. Using $lookup to load references and count them. The process would be similar for embedded relations (without the $lookup). But this doesn't work with hybrid relations.

Checklist

@@ -556,6 +557,8 @@ public function generateCacheKey()
/** @return ($function is null ? AggregationBuilder : mixed) */
public function aggregate($function = null, $columns = ['*'])
{
assert(is_array($columns), new TypeError(sprintf('Argument #2 ($columns) must be of type array, %s given', get_debug_type($columns))));
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We cannot add the type to the argument as it's missing in the parent method. When the value is invalid here, the error comes very late in Query\Builder::toMQL.

Comment on lines 602 to 605
// When the aggregation is per group, we return the results as is.
if ($this->groups) {
return $results;
}
Copy link
Member Author

@GromNaN GromNaN Oct 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trying to support this feature in Laravel, so that withCount on hybrid relations could work.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you just not add withCount on hybrid relations, its a blocker. Also a suggestion It would be better for hybrid to be a separate package instead of being integrated into laravel-mongodb if that could ease the maintenance and focus for other mongodb eloquent methods.

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

Successfully merging this pull request may close these issues.

2 participants