Sequelize, problem getting associations to return

后端 未结 4 1706
旧时难觅i
旧时难觅i 2021-02-15 13:20

I\'m currently experimenting with Sequelize and have two objects, a Person and Position, When getting a list of persons I want to get their position. <

4条回答
  •  渐次进展
    2021-02-15 13:28

    Ok here a complete example how to fix your problem (and yeah that's crap):

    User.findAll().on('success', function(users) {
      var chainer = new Sequelize.Utils.QueryChainer
        , _users  = []
    
      users.forEach(function(u) {
        var emitter = new Sequelize.Utils.CustomEventEmitter(function() {
          u.getPosition().on('success', function(pos) {
            _users.push({user: u, position: pos})
            emitter.emit('success')
          })
        })
        chainer.add(emitter.run())
      })
      chainer.run().on('success', function() {
        res.render('users', {
          title: 'user page',
          users: _users
        })
      })
    })
    

    This will first get all the users, then get the position of each user and save them in the _users-array. Afterwards it renders the page. It's not tested but should do the trick.

提交回复
热议问题