typed-knex
typed-knex copied to clipboard
Get ID after inserting row
Issue type:
[X] Question [ ] Bug report [X] Feature request [ ] Documentation issue
Database system/driver:
[ ] Postgres [ ] MSSQL [X] MySQL [ ] MariaDB [ ] SQLite3 [ ] Oracle [ ] Amazon Redshift
typed-knex version:
[X] latest
[ ] @next
[ ] 0.x.x
(or put your version here)
Is it possible to get ID of the last inserted row? Knex itself has .returning('id')
but typedKnex always returns void with insertItem
so I could not find a way to achieve this.
https://github.com/wwwouter/typed-knex/pull/36
Looks awesome :O I will try to implement it tomorrow.
Thanks! Available in 4.3.0 https://github.com/wwwouter/typed-knex#insertItemWithReturning
I have tested it out and got 2 problems. My console log is:
(in warning colors) .returning() is not supported by mysql and will not have any effect.
TEST 4
My code is:
const userData = await SQLManager.typedKnex
.query(TableCustomers)
.insertItemWithReturning(
new TableCustomers({
email: body.email,
password: encryptedPass,
agreeNewsletter: body.agreeNewsletter,
}),
['id']
);
console.log('TEST', userData);
Meanwhile, the autocomplete is:
- Why does it say .returning() is not supported? Is this function deprecated, should we be using something else?
- Why does autocomplete suggest
.id
as a number if the object itself seems to be the number?
-
It seems that
returning
is only supported by PostgreSQL, MSSQL, and Oracle databases: https://knexjs.org/#Builder-returning -
The function returns
Pick<TableCustomers, 'id'>
and notnumber
.
@wwwouter You should also implement this for update
in addition to insert
. It's been very useful for us so far, but we've been having to make 2 queries on update
. updateItemWithReturning
would be huge!
@bgilman-nyk I added this to v4.5.0. Can you check if this is what you actually need?
@wwwouter I see the change on your repo. Exactly what we need! But when I grabbed latest from npm, it looks like while the src
of the package has been updated, the changes are still not reflected in dist
Not sure what went wrong. Can you try v4.5.1?
Fantastic, thank you!
@Meldiron Can this be closed?
@wwwouter I think the types of these functions don't match what they actually return. For example, if I have some table with an aliased ID field:
@Table("foo")
class Foo {
@Column({ primary: true, name: "foo_id" })
id: number
// ...
}
If I do typedKnex.query(Foo).insertItemWithReturning({ ... }, ["id"])
, the type on that is something close to Pick<Foo, "id">
but what I actually get is something of type { foo_id: number }
.
Seems like either the types should be changed to reflect that, or the functions should be changed to alias the returned columns back to their property names
I see the alias mapping is omitted. Will fix.
@bam365 Could you check to see if it works in v4.7.0?