Skip to content

Commit

Permalink
fix: use correct property name for reading local primary key value
Browse files Browse the repository at this point in the history
FIXES: #1069
  • Loading branch information
thetutlage committed Nov 27, 2024
1 parent ade635f commit 65790bf
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
8 changes: 3 additions & 5 deletions src/orm/base_model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2106,10 +2106,8 @@ class BaseModelImpl implements LucidRow {
client: QueryClientContract
): any {
const modelConstructor = this.constructor as typeof BaseModel
const primaryKeyColumn = modelConstructor.$keys.attributesToColumns.get(
modelConstructor.primaryKey,
modelConstructor.primaryKey
)
const primaryKey = modelConstructor.primaryKey
const primaryKeyColumn = modelConstructor.$keys.attributesToColumns.get(primaryKey, primaryKey)

/**
* Returning insert query for the inserts
Expand All @@ -2126,7 +2124,7 @@ class BaseModelImpl implements LucidRow {
* updating primary key itself
*/
const primaryKeyValue = modelConstructor.selfAssignPrimaryKey
? this.$original[primaryKeyColumn]
? this.$original[primaryKey]
: this.$primaryKeyValue

/**
Expand Down
43 changes: 43 additions & 0 deletions test/orm/base_model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1402,6 +1402,49 @@ test.group('Base Model | persist', (group) => {
assert.lengthOf(users, 1)
assert.equal(users[0].id.toLowerCase(), newUuid)
})

test('use custom name for the local primary key', async ({ fs, assert }) => {
const app = new AppFactory().create(fs.baseUrl, () => {})
await app.init()
const db = await getDb()
const adapter = ormAdapter(db)

const BaseModel = getBaseModel(adapter)

class User extends BaseModel {
static table = 'uuid_users'
static selfAssignPrimaryKey = true

@column({ isPrimary: true, columnName: 'id' })
declare userId: string

@column()
declare username: string

@column()
declare createdAt: string

@column({ columnName: 'updated_at' })
declare updatedAt: string
}

User.boot()

const uuid = '2da96a33-57a0-4752-9d56-0e2485d4d2a4'

const user = new User()
user.userId = uuid
user.username = 'virk'
await user.save()

const newUuid = '4da96a33-57a0-4752-9d56-0e2485d4d2a1'
user.userId = newUuid

await user.save()
const users = await User.all()
assert.lengthOf(users, 1)
assert.equal(users[0].userId.toLowerCase(), newUuid)
})
})

test.group('Self assign primary key', () => {
Expand Down

0 comments on commit 65790bf

Please sign in to comment.