{"record":{"id":"7238cc3ded0f870c","repo":"mongodb/laravel-mongodb","slug":"constraints-on-the-embedded-relation-s-are-not-supported","errorCode":null,"errorMessage":"Constraints on the embedded relation \"%s\" are not supported.","messagePattern":"Constraints on the embedded relation \"(.+?)\" are not supported\\.","errorType":"exception","errorClass":"LogicException","httpStatus":null,"severity":"error","filePath":"src/Helpers/QueriesRelationshipAggregates.php","lineNumber":139,"sourceCode":"            '',\n            sprintf('%s %s %s', $name, $function, strtolower($column)),\n        ));\n\n        return [$name, $alias];\n    }\n\n    private function assertEmbeddedConstraintsSupported(Relation $relation, string $name, Closure $constraints): void\n    {\n        if (! $relation instanceof EmbedsOneOrMany) {\n            return;\n        }\n\n        $subQuery = $relation->getRelated()->newQuery();\n        $constraints($subQuery);\n        $query = $subQuery->getQuery();\n\n        if ($query->wheres || $query->limit !== null || $query->offset !== null || $query->distinct) {\n            throw new LogicException(sprintf(\n                'Constraints on the embedded relation \"%s\" are not supported.',\n                $name,\n            ));\n        }\n    }\n\n    /** @inheritdoc */\n    public function eagerLoadRelations(array $models)\n    {\n        foreach ($this->withAggregates as $alias => $aggregate) {\n            $this->assertAggregateNotUsedInQuery($alias);\n            $this->hydrateAggregate($models, $alias, $aggregate);\n        }\n\n        return parent::eagerLoadRelations($models);\n    }\n\n    /**","sourceCodeStart":121,"sourceCodeEnd":157,"githubUrl":"https://github.com/mongodb/laravel-mongodb/blob/0634653039468ceb0268a69192bdac64469ed043/src/Helpers/QueriesRelationshipAggregates.php#L121-L157","documentation":"When using withAggregate/withCount/withSum etc. on an embedded relation (EmbedsOneOrMany), MongoDB Laravel cannot apply query constraints (where, limit, offset, distinct) to the embedded documents, because aggregates on embedded data are computed in PHP from the parent document, not by a server query. The library throws this LogicException as soon as any constraint closure passed to withAggregate adds one of those clauses.","triggerScenarios":"Calling e.g. Model::withAggregate('embeddedItems:sum(price)', fn($q) => $q->where('active', true)) or withCount('embeds', fn($q) => $q->limit(5)) where the relation is an embedsMany/embedsOne and the closure applies where/limit/offset/distinct.","commonSituations":"Developers migrating from SQL-backed Eloquent where filtering sub-aggregates via closures works; they reuse the same constraint closures for embedded relations and hit the limitation since MongoDB embedded aggregates are computed client-side after reading the parent document.","solutions":["Remove the where/limit/offset/distinct constraints from the closure for the embedded relation.","Filter or limit the embedded documents after fetching, e.g. compute the aggregate manually from $model->relation and filter in PHP with collections.","If filtering is essential, restructure so the data is stored in a separate collection with a HasOneOrMany/BelongsToMany relation, which supports constraints."],"exampleFix":"// before\nOrder::withAggregate('lines:sum(total)', fn ($q) => $q->where('refunded', false))->get();\n// after\nOrder::withAggregate('lines:sum(total)')->get()->each(function ($order) {\n    $order->lines_sum_total = collect($order->lines)->where('refunded', false)->sum('total');\n});","handlingStrategy":"validation","validationCode":"// Check the closure adds no constraints before calling withAggregate on an embedded relation\n$q = $model->related()->getRelated()->newQuery();\n$closure($q);\n$base = $q->getQuery();\nif ($base->wheres || $base->limit !== null || $base->offset !== null || $base->distinct) {\n    throw new LogicException('Constraints are not supported on embedded relation aggregates.');\n}","typeGuard":"function supportsEmbeddedConstraints($relation): bool {\n    return !($relation instanceof \\MongoDB\\Laravel\\Relations\\EmbedsOneOrMany);\n}","tryCatchPattern":"try {\n    $result = Order::withAggregate('lines:sum(total)', fn ($q) => $q->where('active', true))->get();\n} catch (\\LogicException $e) {\n    // fall back to computing the aggregate in PHP\n    $result = Order::withAggregate('lines:sum(total)')->get();\n}","preventionTips":["Do not pass constraint closures when aggregating embedsMany/embedsOne relations.","Filter embedded documents with Laravel collections after fetching the parent.","Move heavily filtered aggregates to a separate collection with hasMany/belongsToMany relations."],"tags":["mongodb","eloquent","embedded-relations","aggregate","logic-exception"],"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"}