2017-10-14 413 views
0

确实TypeORM包括一些functionnality避免这种情况:TypeORM UPSERT - 创建如果不存在

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

回答

0

有已经为它的方法:Repository<T>.save(),它的文档说:

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

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

因此,与typeORM upserting是:

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