nuwave / nuwave/lighthouse

`n+1` problem with eager loading models in different databases (connections)

Open
#2,653 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

question
Dominant language
PHP
Stars
3.5k
Forks
468
Avg merge
3h 9m
Merged PRs (30d)
2

Description

What problem does this feature proposal attempt to solve?

I found n+1 problem with eager loading models in different databases (connections). Currently, the code will not eager load entitles that live on two different connections. I debug and tracked the problem to this specific line at src/Schema/Directives/RelationDirective.php:

if (
    $this->lighthouseConfig['batchload_relations']
    // Batch loading joins across both models, thus only works if they are on the same connection
    && $this->isSameConnection($relation) //  <-- Right here.
) {

Which possible solutions should be considered?

I don't know what is the rationale for this limitation but that should be OK by default to eager load models on different connections. To solve this problem we can either eliminate this limitation or introduce new config variable that allows to override this check at $this->isSameConnection($relation), something like:

    /*
    |--------------------------------------------------------------------------
    | Batchload Relations
    |--------------------------------------------------------------------------
    |
    | If set to true, relations marked with directives like @hasMany or @belongsTo
    | will be optimized by combining the queries through the BatchLoader.
    |
    */

    'batchload_relations' => true,
    'batchload_relations_only_on_same_connections' => true,

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in src/Schema/Directives/RelationDirective.php at the isSameConnection check, then trace the batch-loading configuration and relation path it controls. Define and verify behavior for relations whose models use different connections; done means the selected behavior avoids the reported n+1 without breaking same-connection eager loading.

Written by the indexing model from the issue text.

Assessment

Tech stack
graphql, laravel, php
Domain
api, backend, databases
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.