2017-10-14 412 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 !"}); 
相關問題