{"record":{"id":"ebed721582d28a53","repo":"mongodb/laravel-mongodb","slug":"s-is-not-supported-for-relation-aggregates","errorCode":null,"errorMessage":"%s is not supported for relation aggregates.","messagePattern":"(.+?) is not supported for relation aggregates\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":310,"sourceCode":"            return;\n        }\n\n        if (! DocumentModel::isDocumentModel($relation->getRelated()) || $this->isAcrossConnections($relation)) {\n            throw new LogicException(sprintf(\n                'Aggregating the hybrid relation \"%s\" is not supported. The related model must be stored in MongoDB.',\n                $name,\n            ));\n        }\n\n        if (\n            $relation instanceof HasOneOrMany\n            || $relation instanceof BelongsToMany\n            || ($relation instanceof BelongsTo && ! $relation instanceof MorphTo)\n        ) {\n            return;\n        }\n\n        throw new LogicException(sprintf(\n            '%s is not supported for relation aggregates.',\n            class_basename($relation),\n        ));\n    }\n\n    private function getAggregateParentKey(Relation $relation): ?string\n    {\n        return match (true) {\n            $relation instanceof HasOneOrMany => $relation->getLocalKeyName(),\n            $relation instanceof BelongsTo => $relation->getForeignKeyName(),\n            $relation instanceof BelongsToMany => $relation->getParentKeyName(),\n            default => null,\n        };\n    }\n\n    /** The aggregated value does not exist in the documents, the server cannot use it. */\n    private function assertAggregateNotUsedInQuery(string $alias): void\n    {","sourceCodeStart":292,"sourceCodeEnd":328,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L292-L328","documentation":"Only certain relation types support aggregates in MongoDB Laravel: EmbedsOneOrMany, HasOneOrMany, BelongsToMany, and BelongsTo (except MorphTo). Any other relation class (e.g. MorphTo, MorphToMany variants not covered, or custom relation classes) throws this LogicException naming the relation class via class_basename.","triggerScenarios":"Calling withCount/withSum etc. with a morphTo relation ( polymorphic inverse), e.g. Model::withCount('morphToRelation'), or any custom Relation subclass not in the supported list.","commonSituations":"Polymorphic inverse relations: a commentable morphTo relation cannot be aggregated because the target table/type varies per row; custom relation classes written by the app are also unsupported.","solutions":["Remove withAggregate/withCount on the morphTo/custom relation.","Aggregate per morph type instead: filter by morph type and use withCount on the concrete hasMany relations per type.","Compute the count manually in PHP after fetching parents, grouping by morph type and id."],"exampleFix":"// before\nLike::withCount('likeable')->get(); // morphTo not supported\n// after\n$likes = Like::with('likeable')->get();\n$counts = $likes->groupBy(fn ($l) => $l->likeable::class)->map->count();","handlingStrategy":"validation","validationCode":"// Check relation type before using withAggregate\n$relation = (new Model())->morphToRelation();\nif (!$relation instanceof \\MongoDB\\Laravel\\Relations\\EmbedsOneOrMany\n    && !$relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\HasOneOrMany\n    && !$relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany\n    && (!$relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo || $relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\MorphTo)) {\n    throw new LogicException('Relation type not supported for aggregates.');\n}","typeGuard":"function supportsRelationAggregate(object $relation): bool {\n    return $relation instanceof \\MongoDB\\Laravel\\Relations\\EmbedsOneOrMany\n        || $relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\HasOneOrMany\n        || $relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\BelongsToMany\n        || ($relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\BelongsTo && !$relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\MorphTo);\n}","tryCatchPattern":"try {\n    $result = Model::withCount('morphToRelation')->get();\n} catch (\\LogicException $e) {\n    // compute counts manually grouped by morph type\n    $result = Model::with('morphToRelation')->get();\n}","preventionTips":["Avoid withCount/withSum on morphTo relations; aggregate per concrete morph type instead.","Use only hasOne/hasMany/belongsToMany/belongsTo/embeds relations with aggregates.","Document custom relation classes as unsupported for aggregates."],"tags":["mongodb","eloquent","morph-to","aggregate","unsupported-relation"],"backgroundTag":"unsupported-operation","analyzedSha":"0634653039468ceb0268a69192bdac64469ed043","analyzedAt":"2026-09-15T02:56:37.067Z","contentChangedAt":"2026-09-15T02:56:37.067Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}