adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.02k stars 189 forks source link

Nested lazy load result on wrong internal queries #1039

Open Marian0 opened 5 days ago

Marian0 commented 5 days ago

Package version

20.6.0

Describe the bug

Hello everyone,

I really appreciate your work on Adonis, it is definitely one of the best and more productive frameworks I've ever work with.

While running some nested lazy loading as example:

    const brevet = await Brevet.findOrFail(request.param('id'))
    await brevet.load('activity')
    await brevet.load('athlete')
    await brevet.athlete.load('club')
    await brevet.athlete.load('media')
    await brevet.activity.load('media')
    await brevet.athlete.club.load('media')
    return brevet

I see in DB debugging inspector that if media_id is null on any on the related models, the orm result on triggering those useless DB queries:

Screenshot_23_06_2024__18_15

I managed to fix this by conditionally lazy load models but it would be great to be the ORM enough smart to don't trigger those queries if the requested foreign key is null.

Temporary fix:

    const brevet = await Brevet.findOrFail(request.param('id'))
    await brevet.load('activity')
    await brevet.load('athlete')
    await brevet.athlete.load('club')
    if (brevet.athlete.mediaId) {
      await brevet.athlete.load('media')
    }
    if (brevet.activity.mediaId) {
      await brevet.activity.load('media')
    }
    if (brevet.athlete.club.mediaId) {
      await brevet.athlete.club.load('media')
    }
    return brevet

Any help would be welcomed as I'm also open to dig deeper on this if someone could guide me how to.

Thank you!

Reproduction repo

No response

RomainLanz commented 4 days ago

Hey @Marian0!

The issue seems not to be "nested lazy load" but more about what to do if the FK is null. I recall that this is something we already discussed many times, but I don't remember where or when. I will have to do some search and get back to you.

Marian0 commented 1 day ago

hey @RomainLanz

Thanks for your response actually you are right, it seems to be a missing early return before hitting DB if FK is null

If you give me more insights i can try to submit a PR with a tentative solution