![](/img/trans.png)
[英]Association model not showing in many to many association sequelize.js node
[英]Sequelize.js' association are not rendered on the page
我有两个模型。
var self = {
User: sequelize.define('user', {
id: {type: Sequelize.INTEGER,primaryKey: true,autoIncrement: true},
name: {type: Sequelize.STRING,allowNull: false}
}),
Role: sequelize.define('role', {
id: {type: Sequelize.INTEGER,primaryKey: true,autoIncrement: true},
name: {type: Sequelize.STRING,allowNull: false}
})
}
我还指定了它们之间的关联。
self.User.belongsTo(self.Role);
控制器user.js的一部分:
list: function(req, res){
models.User.findAll({offset: offset, limit: limit}).success(function (users) {
if (req.params.format == 'html') {
res.render('admin/user/list.html', {
title: 'Users',
layout: layout,
users: users
});
} else if (req.params.format == 'json') {
res.json(users);
}
}
在视图list.html中:
<% users.forEach(function(user){ %>
<tr>
<td><%= user.id %></td>
<td><a href="/admin/user/<%= user.id %>/show.html"><%= user.name %></a></td>
<td><%= user.getRole().name %></td>
</tr>
<% } %>
如果我们调用/list.html,则会为每个用户在页面上获得未定义的角色。
如果调用/list.json,我们将获得:
[{"id":1,"name":"user1", "role_id":1},
[{"id":2,"name":"user2", "role_id":1},
[{"id":3,"name":"user3", "role_id":2},
...
如何在list.html和json响应中获得每个用户的角色? 还是有更好的方法?
谢谢。
你需要打电话
models.User.findAll({offset: offset, limit: limit, include: [models.Role]})
有关更多详细信息,请参见http://sequelizejs.com/documentation#models-eager-loading
没有获得关联角色的原因是这样的事实,即异步获取该用户的角色。 这意味着1.)您需要使用user.getRole().success(function(role){})
和2.)您需要读取控制器中的角色,因为EJS无法处理异步性。 希望有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.