繁体   English   中英

有没有办法在 TypeORM 中访问 `last_inserted_id`?

[英]Is there a way to access `last_inserted_id` in TypeORM?

具体来说,有没有办法在 TypeORM 事务中访问 last_inserted_id? IE:

 try {
        // transaction
        await getManager().transaction(async (trManager): Promise<any> => {

            const company = new Company();
            const savedCompany = await trManager.save(company);
            const companyId = savedCompany.lastInsertedId;

            // ..............more saves..............//

            // await trManager.save(otherEntityUsingCompanyId);

        });
    } catch (err) {
        console.error("err: ", err);         
    }

我已经彻底浏览了文档(诚然,如果我错过了一些东西,可能还不够彻底)并且没有看到任何东西。 我发现看起来相似的最接近的文档是:

const userId = manager.getId(user); // userId === 1

这似乎是一个足够常见的用例,我假设我错过了一些东西,这就是为什么我犹豫不决提出问题。 任何帮助,将不胜感激。 谢谢!

注意 :请注意,大约从原始答案开始,我就没有使用TypeORM,因此现在可能有更好的方法。

弄清楚了。 使用returning方法...

const inserts = await getConnection()
            .createQueryBuilder()
            .insert()
            .into(Company)
            .values([
                { Name: "abcdef", Address: "456 denny lane" }, 
                { Name: "ghijkil", Address: "899 ihop lane" }
            ])
            .returning("INSERTED.*")
            .printSql()
            .execute();

// `inserts` holds array of inserted objects
OUTPUT or RETURNING clause only supported by Microsoft SQL Server or PostgreSQL databases.

对于MySql,您可以从结果中获取last_insert_id。 看起来如下。

 InsertResult { identifiers: [ { id: 1 } ], generatedMaps: [ { id: 1, creationTime: 2019-09-03T10:09:03.000Z, lastUpdate: 2019-09-03T10:09:03.000Z } ], raw: OkPacket { fieldCount: 0, affectedRows: 1, insertId: 1, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0 } } 

const companyInsert = new Company({/* set properties */});

const res = await getConnection()
    .getRepository(Company)
    .insert(companyInsert);

const insertedId_option_A = companyInsert.id;
const insertedId_option_B = Number(res.identifiers[0].id);

A) 出现 TypeORM 插入 DB 后会修改传入的对象。 此外,它将添加/填充由默认列值填充的所有属性。

B) Willow-Yang 的扩展答案。

使用 MySQL 驱动程序和 TypeORM 0.2.32 测试

ps 不确定交易的具体情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM