adonisjs / lucid

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

Preload relationship does not work #1019

Open anhc0de opened 8 months ago

anhc0de commented 8 months ago

Package version

20.4.0

Describe the bug

I have set up relationships as below

User.ts

  @hasMany(() => Task, {
    foreignKey: 'assignedToId',
  })
  declare assignedTasks: HasMany<typeof Task>

Task.ts

 @column({ columnName: 'assigned_to_id' })
  declare assignedToId: number
  @belongsTo(() => User, {
    foreignKey: 'assignedToId',
  })
  declare assignedTo: BelongsTo<typeof User>

Query

const records = await Task.query()
      .preload('assignedTo')
      .orderBy('updated_at', 'desc')
      .orderBy('created_at', 'desc')
      .paginate(page, limit)

records.forEach((user) => {
      logger.info('assignedToId=%s preload::assignedTo=%o', user.assignedToId, user.assignedTo)
    })

Result

CleanShot 2024-03-25 at 16 42 59@2x

DB tables

User

CleanShot 2024-03-25 at 16 44 22@2x

Task

CleanShot 2024-03-25 at 16 45 06@2x

Reproduction repo

No response