sequelize has many associations update

i am building resful api with node js and sequelize (mysql).

i have two models with (event) has many (users).

for creating event with models i am doing this :

 add(req, res) {
    return event.create(
      {
        name: req.body.name,
        users: req.body.users,
      },
      {
        include: [
          {
            model: User,
            as: "users",
          },
        ],
      }
    )

it’s working fine .

but when i want to update i have big issue here.
for example my current events looks like :

"events" : [
{
 "id" : 1 ,
"name" :"name"
"users" :[
{
"id" :1 ,
"name" :"name1",
},
{
"id" :2 ,
"name" :"name2",
}
]
}]

what i want to achieve :
i want to update users :
if the id of user exists in the request i want to update the user ,but if the id doesn’t exists in the request i want to delete do user.

how i can do that in sequelize and node js .i’m stack here.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Show your router where you try to handle that logic.
When you say that user exists do you mean user exists at all or only belongs to requested event, please be more specific!!!

// lets say you want to update users of event id=1
const event = await Event.findByPk(1)
// you can get users belonging to event by association mixins
const users = await event.getUsers()
// loop through users to update them
for (let i=0; i < users.length; i++) {
  // put your logic to make changes to users
  if (users[i].getDataValue('id') == 1) {
    await event.removeUser(users[i])
  }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x