Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wojo1206 opened this issue Jan 15, 2025 · 2 comments
Open
Labels
question Request for support or clarification

Comments

@wojo1206
Copy link

wojo1206 commented Jan 15, 2025

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,
@spawnia
Copy link
Collaborator

spawnia commented Jan 23, 2025

The reason for this is right there in the comment:

Batch loading joins across both models

By joins i mean an actual SQL JOIN statement. A single database statement involves the tables of both models.

@spawnia spawnia added the question Request for support or clarification label Jan 23, 2025
@wojo1206
Copy link
Author

Hmm, joins across multiple databases are fine as long as the databases are on the same server instance. The concept of multi-database system in Laravel means that you have set multiple connections even if your databases are on the same instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Request for support or clarification
Projects
None yet
Development

No branches or pull requests

2 participants