{"record":{"id":"44751093086e463a","repo":"mongodb/laravel-mongodb","slug":"aggregating-the-hybrid-relation-s-is-not-supported-the","errorCode":null,"errorMessage":"Aggregating the hybrid relation \"%s\" is not supported. The related model must be stored in MongoDB.","messagePattern":"Aggregating the hybrid relation \"(.+?)\" is not supported\\. The related model must be stored in MongoDB\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":296,"sourceCode":"\n        if (is_scalar($value) || $value instanceof Stringable) {\n            return (string) $value;\n        }\n\n        throw new InvalidArgumentException(sprintf(\n            'The relation key of type \"%s\" cannot be used to match aggregated values.',\n            get_debug_type($value),\n        ));\n    }\n\n    private function assertAggregateRelationSupported(Relation $relation, string $name): void\n    {\n        if ($relation instanceof EmbedsOneOrMany) {\n            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    }","sourceCodeStart":278,"sourceCodeEnd":314,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L278-L314","documentation":"Relation aggregates (withCount/withSum/withAvg/withMin/withMax/withExists) require the related model to also be a MongoDB document model on the same connection, since the aggregation runs as a MongoDB query against the related collection. If the related model is a SQL Eloquent model (hybrid relation) or lives on a different connection, a LogicException is thrown.","triggerScenarios":"Calling MongoModel::withCount('sqlRelation') where the relation's getRelated() is an Illuminate\\Database\\Eloquent\\Model (not MongoDB\\Laravel\\Eloquent\\Model), or the related model uses a different database connection (isAcrossConnections).","commonSituations":"Applications migrating partially from MySQL/Postgres to MongoDB: some models still extend the base Eloquent Model; or MongoDB models configured with different connection names in config/database.php.","solutions":["Make the related model extend MongoDB\\Laravel\\Eloquent\\Model so it is stored in MongoDB.","Ensure both models use the same MongoDB connection name.","Compute the aggregate manually: load the parent, then query the SQL side separately and set the attribute."],"exampleFix":"// before\nclass Comment extends \\Illuminate\\Database\\Eloquent\\Model { ... } // SQL model\n// after\nclass Comment extends \\MongoDB\\Laravel\\Eloquent\\Model { ... } // MongoDB model, same connection\nPost::withCount('comments')->get();","handlingStrategy":"validation","validationCode":"// Before aggregating, check the related model is a MongoDB model on the same connection\n$relation = (new MongoParent())->relation();\nif (!\\MongoDB\\Laravel\\Eloquent\\Model::isDocumentModel($relation->getRelated())) {\n    throw new LogicException('Related model must be stored in MongoDB.');\n}","typeGuard":"function isMongoRelation(object $relation): bool {\n    return $relation instanceof \\Illuminate\\Database\\Eloquent\\Relations\\Relation\n        && \\MongoDB\\Laravel\\Eloquent\\Model::isDocumentModel($relation->getRelated());\n}","tryCatchPattern":"try {\n    $posts = Post::withCount('comments')->get();\n} catch (\\LogicException $e) {\n    // hybrid relation: compute counts separately per store\n    $posts = Post::get();\n    $counts = Comment::whereIn('post_id', $posts->modelKeys())->groupBy('post_id')->selectRaw('post_id, count(*) c')->pluck('c', 'post_id');\n}","preventionTips":["Ensure all models in relations extend MongoDB\\Laravel\\Eloquent\\Model.","Use the same connection name for both sides of the relation.","Plan migrations so both sides of a relation move to MongoDB together."],"tags":["mongodb","eloquent","hybrid-relations","aggregate","sql"],"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"}