typescript TypeORM upsert - 如果不存在则创建

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46745688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:48:50  来源:igfitidea点击:

TypeORM upsert - create if not exist

typescripttypeorm

提问by BeyondTheSea

Does TypeORM include some functionnality to avoid this :

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

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;
}

Something like :

就像是 :

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

回答by BeyondTheSea

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

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

TypeORM upsert feature request

TypeORM upsert 功能请求

Partial solution :

部分解决方案:

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();


Old answer actually points to the "update" way of doing what OP was asking for :

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

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

已经有一种方法了:Repository<T>.save(),其中文档说:

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

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

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.

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

So upserting with typeORM is :

所以使用 typeORM 进行更新是:

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

回答by danielmhanover

There is now a librarythat plugs into TypeORM to help do this.

现在有一个库可以插入 TypeORM 来帮助做到这一点。

回答by Josh Gude

For anyone looking for a way to upsert multiple records and is using Postgres and TypeORM, you're able to access the row you're attempting to update/insert via the excluded keyword.

对于任何正在寻找插入多条记录的方法并正在使用 Postgres 和 TypeORM 的人,您都可以通过 exclude 关键字访问您尝试更新/插入的行。

const posts = [{ id: 1, title: "First Post" }, { id: 2, title: "Second Post" }];

await connection.createQueryBuilder()
        .insert()
        .into(Post)
        .values(posts)
        .onConflict(`("id") DO UPDATE SET "title" = excluded."title"`)
        .execute();

回答by naval

Note in your entity as user here

在您的实体中作为用户注意这里

@OneToMany(type => Post, post => post.user, {
        cascade: true
    })
    posts: Post[];


export const saveAllPosts = async (req: Request, res: Response) => {
    const userRepository = getManager().getRepository(User);
    const postRepository = getManager().getRepository(Post);
    let i;
    let newUsers:any = [];
    let  newUser:any = {};
    let  newPost:any = {};
    for(i=1; i<=6; i ++) {
        newUser = await userRepository.findOne({ 
            where: { id: i} 
        });
        if(typeof newUser == "undefined") {
            newUser = new User();
            console.log("insert");
        } else  {
            console.log("update");
        }           
        newUser.name  = "naval pankaj test"+i;   

        newPost = await postRepository.findOne({ 
            where: { userId: i} 
        });
        if(typeof newPost == "undefined") {
            newPost = new Post();
            console.log("post insert");
        } else  {
            console.log("post update");
        }
        newPost.title = "naval pankaj add post title "+i;
        newUser.posts = [newPost];
        newUsers.push(newUser);     
    }
    await userRepository.save(newUsers);  
    res.send("complete");
};