1
我想加入使用Sequelize的兩個表包括這樣:訪問內部聯接使用從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:
用戶(它不相當覺得不對勁具有代替boardMembers這裏的hasMany,但我並不想在用戶表的外鍵字段)
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: '[email protected]',
access: '0',
boardMembers: [Object] },
...
]
任何幫助是多感謝!
感謝,
Freece
恩,很抱歉地說這不起作用。嘗試使用:'models.user.findAll({include:[{nested:true,all:true,model:models.boardMember,required:true}]})'及其幾個不同版本。謝謝你的提示,但! – Freece
如果使用all:true選項,則不需要指定模型。從我的問題中可以看出,您正在檢索相關的boardMemebers(boardMembers:響應數組上的'boardMembers:[Object]'),但在您的模板中,您將boardMember屬性看作是單個對象的位置,但關係是多個 – yeiniel
是的,你是對的。我一直在想這是錯誤的。我意識到我需要做的是爲HandleBars創建一個自定義幫助器。 – Freece