Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between set and add method in sequelize instance?

Tags:

sequelize.js

Docs said :

  • Add: Associate one or more target rows with this.
  • Set: Set the associated models by passing an array of persisted instances or their primary keys.

Since the docs not provide any example, i found it very confusing. Is add will add foreignkey to associated row and Set will set the forreignkey of this to associated row ?

like image 647
PhmNgocNghia Avatar asked Jul 23 '18 02:07

PhmNgocNghia


1 Answers

Let's look at a 1:M example: Project has many Tasks.

With set "everything that is not in the passed array will be un-associated". This means that if you set tasks for the second time on the same project, you will replace the previous tasks.

Whereas with add, you don't have to worry about old tasks being replaced; both old and new tasks will be added

project.setTasks([task1, task2]).then(() => {
  // saved!
})

// remove the association with task1
project.setTasks([task2]).then(associatedTasks => {
  // you will get task2 only
})

As a side effect, passing an empty array into set will remove all tasks

// remove 'em all
project.setTasks([]).then(associatedTasks => {
  // you will get an empty array
})

// or remove 'em more directly
project.removeTask(task1).then(() => {
  // it's gone
})

http://docs.sequelizejs.com/manual/tutorial/associations.html#associating-objects

like image 135
Alex Sicoe Avatar answered Oct 11 '22 22:10

Alex Sicoe