TypeORM upsert - 如果不存在则创建 [英] TypeORM upsert - create if not exist

查看:154
本文介绍了TypeORM upsert - 如果不存在则创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeORM 是否包含一些功能来避免这种情况:

Does TypeORM include some functionnality to avoid this :

let contraption = await thingRepository.findOne({ name : "Contraption" });

if(!contraption) // Create if not exist
{
    let newThing = new Thing();
    newThing.name = "Contraption"
    await thingRepository.save(newThing);
    contraption = newThing;
}

类似:

let contraption = await thingRepository.upsert({ name : "Contraption" });

推荐答案

正如 Tomer Amir 所指出的,目前有一个针对真正的 upsert 的部分解决方案,并且在 TypeORM 的存储库上打开了 ATM 功能请求:

As pointed out by Tomer Amir, there is currently a partial solution for real upsert and a feature request is ATM opened on TypeORM's repository :

TypeORM upsert 功能请求

部分解决方案:

await connection.createQueryBuilder()
        .insert()
        .into(Post)
        .values(post2)
        .onConflict(`("id") DO NOTHING`)
        .execute();

await connection.createQueryBuilder()
        .insert()
        .into(Post)
        .values(post2)
        .onConflict(`("id") DO UPDATE SET "title" = :title`)
        .setParameter("title", post2.title)
        .execute();

<小时>

旧答案实际上指向了执行 OP 要求的更新"方式:

已经有一个方法:Repository.save(),其中文档说:

There's already a method for it : Repository<T>.save(), of which documentation says :

在数据库中保存所有给定的实体.如果实体不存在于然后数据库插入,否则更新.

Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.

但如果您不指定 id 或唯一字段集,则 save 方法无法知道您正在引用现有的数据库对象.

But if you do not specify the id or unique set of fields, the save method can't know you're refering to an existing database object.

因此使用 typeORM 进行 upserting 是:

So upserting with typeORM is :

let contraption = await thingRepository.save({id: 1, name : "New Contraption Name !"});

这篇关于TypeORM upsert - 如果不存在则创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆