Sequelize,让关联返回的问题 [英] Sequelize, problem getting associations to return

查看:50
本文介绍了Sequelize,让关联返回的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在试验 Sequelize 并有两个对象,一个 PersonPosition,当我想获得一个人的列表时,我想得到他们的位置.

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.

型号:

var User = sequelize.define('user', {
    first_name: Sequelize.STRING,
    last_name: Sequelize.STRING 
});

var Position = sequelize.define('position', {
    name: Sequelize.STRING,
    affiliation: Sequelize.STRING
});

Position.hasMany(User, { foreignKey : 'position_id' });
User.belongsTo(Position, { foreignKey : 'position_id'});

我的查询:

User.findAll({ fetchAssociations: true }, function(results) {
    //I've tried doing some work in here, but haven't found the correct procedure. 
}).on('success', function(results) {
    res.render('users', {
        title: 'user page',
        users: results
    });
});

查看日志它根本不会查询Person.我需要使用 queryChaining 吗?从我能够找到的文档中,它似乎应该自动获取关联.

Watching the log it never queries Person at all. Do I need to use queryChaining? From the documentation I was able to find it appeared it should auto fetch associations.

推荐答案

好的,这里有一个如何解决您的问题的完整示例(是的,这是废话):

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

这将首先获取所有用户,然后获取每个用户的位置并将它们保存在_users-array 中.之后它呈现页面.它没有经过测试,但应该可以解决问题.

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.

这篇关于Sequelize,让关联返回的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆