续集,让关联返回的问题 [英] Sequelize, problem getting associations to return
问题描述
我目前正在尝试使用 Sequelize 并有两个对象,一个 Person
和 Position
,在获取人员列表时我想获得他们的位置.
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
.我需要使用查询链吗?从文档中我发现它似乎应该自动获取关联.
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.
这篇关于续集,让关联返回的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!