簡體   English   中英

sequelize 有很多關聯更新

[英]sequelize has many associations update

我正在使用 node js 和 sequelize (mysql) 構建 resful api。

我有兩個模型(事件)有很多(用戶)。

為了使用模型創建事件,我正在這樣做:

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

它工作正常。

但是當我想更新時,我在這里遇到了大問題。 例如我當前的事件看起來像:

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

我想要實現的目標:我想更新用戶:如果請求中存在用戶的 id,我想更新用戶,但如果請求中不存在該 id,我想刪除 do 用戶。

我如何在 sequelize 和 node js 中做到這一點。我在這里堆棧。

向您的路由器展示您嘗試處理該邏輯的位置。 當你說用戶存在時,你的意思是用戶完全存在還是只屬於請求的事件,請更具體!!!

// 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])
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM