web-dev-qa-db-ja.com

ループバックアプリケーションで挿入または更新(アップサート)

ループバックフレームワークを使用してAPIを開発しました。つまり、テーブルにinsert or updateする必要があります。

私のテーブルは以下のようになります:

userid  bbid saved  id(PK)
  1      5    1000   1

したがって、次回if(bbid = 5)が上記の行を更新する必要がある場合、bbid = 5が存在しない場合は、上記のテーブルに挿入する必要があります。

私は以下を試しました:

app.models.modelname.upsert({
  bbid: bb.id,
  saved: Saved,
  userid: 1
}, function(err, res) {}); 

コンポジットIDの編集:

app.models.modelname.upsert({
  bbid: vvvv.bbid,
  userid: 1,
  saved: amountSaved
}, function(err, res) {});   

また、ループバックドキュメントを通過しました

    upsert - checks if the instance (record) exists, based on the designated 
ID property, which must have a unique value; if the instance already exists, 
the method updates that instance.  Otherwise, it inserts a new instance.

しかし、私の場合はbbid not idをチェックする必要があります

しかし、その毎回挿入。あなたのアイデアを共有してください。前もって感謝します

UPSERTの編集:

私のプロセスは次のとおりです。

Fetch from table1 and loop that response and calculate the saved and upsert it into another table(table2 (this is where upsert should happen)). Also the fetching from table1 will happen frequently so suppose consider if is happens 2nd time it should update the already present bbid..
6
Subburaj

findOrCreate メソッドは次のように使用できます。

app.models.modelname({where: {bbid:bb.id} }, {bbid:bb.id, saved: Saved, userid:1}, function(err, instance) {
    if (err){
        cb(null, err);
    }
        cb(null, instance);  
    });
6
conradj

ループバックには2つのメソッドがあります。1つは単純なアップサートで、もう1つはupsertWithWhereです。where条件に基づいて挿入または更新するには、upsertWithWhereメソッドを使用する必要があります。upsertはデータのみを挿入します。あなたが使用している

app.models.modelname.upsert({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

代わりに使用する

app.models.modelname.upsertWithWhere({bbid:bb.id, saved: Saved, userid:1}
          ,function(err, res){});

これはあなたの問題を解決します。

注:これは単一のインスタンスのみを更新します。条件の結果で複数のインスタンスが返されると、エラーがスローされます。

2
Ghulam Hussain