mongodb/laravel-mongodb · error · LogicException

Aggregating the hybrid relation

Error message

Aggregating the hybrid relation "%s" is not supported. The related model must be stored in MongoDB.

What it means

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.

Solutions

  1. Make the related model extend MongoDB\Laravel\Eloquent\Model so it is stored in MongoDB.
  2. Ensure both models use the same MongoDB connection name.
  3. Compute the aggregate manually: load the parent, then query the SQL side separately and set the attribute.

Example fix

// before
class Comment extends \Illuminate\Database\Eloquent\Model { ... } // SQL model
// after
class Comment extends \MongoDB\Laravel\Eloquent\Model { ... } // MongoDB model, same connection
Post::withCount('comments')->get();
Defensive patterns

Strategy: validation

Validate before calling

// Before aggregating, check the related model is a MongoDB model on the same connection
$relation = (new MongoParent())->relation();
if (!\MongoDB\Laravel\Eloquent\Model::isDocumentModel($relation->getRelated())) {
    throw new LogicException('Related model must be stored in MongoDB.');
}

Type guard

function isMongoRelation(object $relation): bool {
    return $relation instanceof \Illuminate\Database\Eloquent\Relations\Relation
        && \MongoDB\Laravel\Eloquent\Model::isDocumentModel($relation->getRelated());
}

Try / catch

try {
    $posts = Post::withCount('comments')->get();
} catch (\LogicException $e) {
    // hybrid relation: compute counts separately per store
    $posts = Post::get();
    $counts = Comment::whereIn('post_id', $posts->modelKeys())->groupBy('post_id')->selectRaw('post_id, count(*) c')->pluck('c', 'post_id');
}

Prevention

When it happens

Trigger: 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).

Common situations: 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.

Understand the failure class

Background: UnsupportedOperationException and "is not supported" errors: when a library deliberately refuses a call — this error's family across 30 libraries.

Related errors


AI-assisted analysis of mongodb/laravel-mongodb@0634653039 (2026-09-15). Data as JSON: /api/errors/44751093086e463a. Report an issue: GitHub.

Appendix: source

Thrown at src/Helpers/QueriesRelationshipAggregates.php:296

        if (is_scalar($value) || $value instanceof Stringable) {
            return (string) $value;
        }

        throw new InvalidArgumentException(sprintf(
            'The relation key of type "%s" cannot be used to match aggregated values.',
            get_debug_type($value),
        ));
    }

    private function assertAggregateRelationSupported(Relation $relation, string $name): void
    {
        if ($relation instanceof EmbedsOneOrMany) {
            return;
        }

        if (! DocumentModel::isDocumentModel($relation->getRelated()) || $this->isAcrossConnections($relation)) {
            throw new LogicException(sprintf(
                'Aggregating the hybrid relation "%s" is not supported. The related model must be stored in MongoDB.',
                $name,
            ));
        }

        if (
            $relation instanceof HasOneOrMany
            || $relation instanceof BelongsToMany
            || ($relation instanceof BelongsTo && ! $relation instanceof MorphTo)
        ) {
            return;
        }

        throw new LogicException(sprintf(
            '%s is not supported for relation aggregates.',
            class_basename($relation),
        ));
    }

View on GitHub (pinned to 0634653039)