简体   繁体   English

如何使用Sequelize将ID传递到其关联记录

[英]How to pass id to its associated records with Sequelize

I'm building an app with Express on backend, Postgres for db and Sequelize for ORM. 我正在后端构建Express的应用程序,用于DB的Postgres和用于ORM的Sequelize。

I have 3 associated models: 我有3个相关模型:

Post
Event
Publishing , belongs to Post , belongs to Event Publishing ,属于Post ,属于Event

When I publish my Post , I update its state to 2, I need to create an Event and Publishing . 发布Post ,将其状态更新为2,我需要创建一个Event and Publishing Publishing will have the postId and eventId , among other things that I'm passing with a query. Publishing将具有postIdeventId ,以及我随查询传递的其他内容。 I tried the following code, it changes the state of the Post, creates an Event and Publishing, but they are not related to each other. 我尝试了以下代码,它更改了Post的状态,创建了一个Event,并发布了它们,但它们彼此之间并不相关。

  publishPost(req) {
    return new Promise((resolve, reject) => {
      async.parallel({
        changeState: (callback) => {
          Post.findAll({
            where: { id: req.query.post_id },
            attributes: ['id', 'state']
          })
          .then((updateState) => {
            updateState.forEach((postState) => {
              postState.updateAttributes({ state: 2 });
            });
          })
          .then((updatedState) => {
            callback(null, updatedState);
          });
        },
        createEvent: (callback) => {
          Event.create({
            instructions: req.query.instructions,
          })
          .then((createdEvent) => {
            callback(null, createdEvent);
          });
        },
        createPublishing: (callback) => {
          Publishing.create({
            start_date: req.query.startDate,
            end_date: req.query.endDate,
          })
          .then((createdPublishing) => {
            callback(null, createdPublishing);
          });
        }
      }, (error, result) => {
        resolve(result);
      });
    });
  }

How can I pass the IDs of the two records to the third model? 如何将两个记录的ID传递给第三个模型?

There are several problems with your implementation! 您的实现存在几个问题! First of all, your promise never rejects. 首先,您的承诺永远不会拒绝。

Despite of that, you don't actually need to create a promise or use async for this, neither do you want them to run in parallel: If creating a Publishing record needs information about the Event , then you'd want to create first the event, so that you have its id , THEN pass it in the input for the publishing. 尽管如此,您实际上并不需要创建Promise或使用async,也不希望它们并行运行:如果创建Publishing记录需要有关Event信息,那么您首先要创建事件,以使其具有id ,然后将其传递到发布的输入中。

Another important thing, take a look at this piece of code: 另一个重要的事情,看一下这段代码:

  .then((updateState) => {
    updateState.forEach((postState) => {
      postState.updateAttributes({ state: 2 });
    });
  })
  .then((updatedState) => {
    callback(null, updatedState);
  });

Inside the first then, you are making multiple updates, which are promises. 在第一个之后,您将进行多个更新,这是一个承诺。 They will be dispatched and you never get their values back. 他们将被派遣出去,而您将永远无法收回他们的价值观。 Let me explain: 让我解释:

Think if you have just one update to make. 考虑一下您是否需要进行一次更新。 It would be like this: 就像这样:

  .then((updateStates) => {
    return updateStates[0].updateAttributes({ state: 2 });
  })

See, we are returning a promise (in this case the update), so the next then will only be called when the update resolves. 你看,我们正在返回一个承诺(在这种情况下更新),所以未来then当更新可解决才会被调用。

If we do this: 如果我们这样做:

  .then((updateStates) => {
    updateStates[0].updateAttributes({ state: 2 });
  })

It will dispatch the update (which takes time) but because you didn't return it, it will pass through and return nothing. 它将分派更新(这需要时间),但是因为您没有返回更新,它会通过并且不返回任何内容。 Check this out: 看一下这个:

 var promise1 = new Promise(function(resolve, reject) { setTimeout(function(){ resolve('foo') }, 2); }); var promise2 = new Promise(function(resolve, reject) { setTimeout(function(){ resolve('foo2') }, 2); }); promise1 .then(function(result){ promise2 }) .then(function(result){ console.log(result) //will print undefined }) promise1 .then(function(result){ return promise2 }) .then(function(result){ console.log(result) //will print foo2 }) 

So, you are calling multiple updates without getting their values back; 因此,您正在调用多个更新而没有获取其值。 if they fail, you'd never know. 如果他们失败了,你永远不会知道。

Just one more thing: if something goes wrong along the way, you probably want to rollback all the changes made so far, for that, you should use transactions. 只是一件事:如果在此过程中出现问题,您可能要回滚到目前为止所做的所有更改,为此,您应该使用事务。

Maybe you should try something like this (not tested): 也许您应该尝试这样的事情(未经测试):

return Post.sequelize.transaction(function (t) {

    Post.findAll({
      where: { id: req.query.post_id },
      attributes: ['id', 'state']
    })
    .then((updatedStates) => {
      var promises = []
      updatedStates.forEach((postState) => {
        promises.push(postState.updateAttributes({ state: 2 },  {transaction: t}));
      });
      return Promise.all(promises);
    })
    .then((results) => {
      return Event.create({
        instructions: req.query.instructions,
      }, {transaction: t})
    })
    .then((createdEvent) => {
      return Publishing.create({
        post_id: req.query.post_id,
        event_id: createdEvent.id, //or event_id, depends on your model
        start_date: req.query.startDate,
        end_date: req.query.endDate,
      }, {transaction: t})
    });

}).then(function (result) {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Sequelize ORM Node js 仅获取关联记录 - How to get only the associated records using Sequelize ORM Node js 如何获取关联的关联id是给定值的记录 - How to get records where associated's associated_id is a given value Sequelize:查找基于相关属性的记录到多个记录 - 但仍然返回所有相关记录? - Sequelize: Find Records Based on Associated BelongsToMany Record— But Still Return All Associated Records? 如何从sequelize中的关联表中获取数据 - How to get data from associated table in sequelize 有没有办法按父子记录与其子记录关联的最早日期对其进行排序? - Is there a way to sort a parent record by the earliest date associated with its child records? 仅当其所有关联记录均符合条件时才返回记录 - Only return a record when all its associated records match the conditions 如何使用 Sequelize 监听数据库中的新记录? - How to listen for new records in database with Sequelize? 如何在postgres sequelize中使用updateAttributes更新所有记录 - how to update all records with updateAttributes in postgres sequelize 如何通过关联查询续集模型,但包含所有关联对象? - How to query sequelize model by association, but include all associated objects? Sequelize:如何通过关联表的列的总和查询父列 - Sequelize: How to query a parent column by the sum of an associated table's column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM