7

具体来说,有没有办法在 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

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

4

3 回答 3

8

注意:请注意,大约从最初的答案开始,我就没有使用过 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
于 2017-11-21T23:19:23.910 回答
3
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 } }

于 2019-09-03T10:17:09.800 回答
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会在插入数据库后修改传递的对象。此外,它将添加/填充默认列值填充的所有属性。

B)杨柳的扩展答案。

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

ps不确定事务的具体情况。

于 2021-11-17T23:43:25.937 回答