我正在尝试使用Sequelize包含的两个表格加入:
models.user.findAll({include: {model: models.boardMember, required:true}})
.then(function(board) {
console.log(board);
res.render('contact', { title: 'Kontakt', board: board });
});
我的模型使用sequelize express example:
用户(在这里使用hasMany而不是在boardMembers中感觉不对,但我不想在users表中使用外键字段)
module.exports = function(sequelize, DataTypes) {
var user = sequelize.define('user', {
//lots of normal user fields(username, password, access...
}, {
classMethods: {
associate: function(models) {
user.hasMany(models.boardMember, {
foreignKey: {
allowNull: false
}
});
}
}
});
return user;
};
boardMember
module.exports = function(sequelize, DataTypes) {
var boardMember = sequelize.define('boardMember', {
post: {
type: DataTypes.STRING,
unique: false,
allowNull: false
}
});
return boardMember;
};
然后我想使用把手访问表格中返回的数据:
{{#each board}}
<tr>
<td>{{boardMembers.post}}</td>
<td>{{firstName}} {{surName}}</td>
<td>{{email}}</td>
</tr>
{{/each}}
这是我弄错的地方(我想)。显示姓名和电子邮件,但不显示帖子。我也尝试过只使用帖子,但无济于事。我认为这很奇怪,因为生成的查询看起来像这样(我删除了createdAt
和updatedAt
列,使其缩短,以供您阅读):
SELECT
`user`.`id`, `user`.`username`, `user`.`password`,
`user`.`firstName`, `user`.`surName`, `user`.`email`, `user`.`access`,
`boardMembers`.`id` AS `boardMembers.id`, `boardMembers`.`post` AS `boardMembers.post`,
`boardMembers`.`userId` AS `boardMembers.userId`
FROM
`users` AS `user`
INNER JOIN
`boardMembers` AS `boardMembers` ON `user`.`id` = `boardMembers`.`userId`;
console.log输出类似这样的内容(数据明显改变了):
[ Instance {
dataValues:
{ id: 2,
username: 'username',
password: 'hashedPassword',
firstName: 'User',
surName: 'Name',
email: 'user@name.com',
access: '0',
boardMembers: [Object] },
...
]
任何帮助非常赞赏!
谢谢,
Freece
答案 0 :(得分:0)
根据sequelize documentation,include属性的值是一个列表。
您可以尝试使用特殊值include: [{ all: true, nested: true }]
,看看它是否适合您。
此外,您的模板存在问题,因为您已经建立了一对多的关系,因此模型实例的boardMemebers
属性是数组。