2

I create an API that updates a record associated with a foreign key

  1. if I just put a value to items so I want it to return remove other values that I don't put

  2. if I edit some value in items so I want it to return the value that I edited

  3. if I put value over value of items so I want it to return the old value of items and the value that I put over

example: const record = {id:1,name:"abc",items:[{id:1,name:"abc",recordId:1},{id:2,name:"abcd",recordId:1}]}
const update = await dbRecord.update({id,name},{where: {id: req.params.id},include:[model:'items',id:[1,2]});
Raibann
  • 21
  • 4
  • 1
    Unfortunately you can't use `include` option in `update` call and it's related to SQL inability to update different records with different columns/values or even several tables at once. – Anatoly Jan 14 '23 at 13:10

2 Answers2

1

You can use Sequelize mixins. Sequelize has special methods that uses the prefix get add set concatenated with the model name.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 19 '23 at 19:27
0
const update = await dbRecord.update(
  { id, name },
  { where: { id: req.params.id } }
);
//array get from body
ex: array = [
  { id: 1, name: "abc", recordId: 1 },
  { id: 2, name: "abcd", recordId: 1 },
];
const itemId = array.map((arr) => arr.id);
// result = [1,2]

await dbItems.bulkCreate(array, {
  updateOnDuplicate: ["name"],
});

for (var i = 0; i < update.items.length; i++) {
  const item = update.items[i];
  if (!itemId.includes(container.id)) {
    await container.destroy();
  }
}

so it create update delete in once time.

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
Raibann
  • 21
  • 4