我能够对我的 images
表进行查询并正确提取我的记录,但我希望修改我的查询以包含来 self 的外部的 body
字段通过 description_id
连接到我的主表的表。我已经在数据库中创建了关系,但不确定是否需要对我的 Sequelize 模型代码进行更改,或者对查询进行简单更改是否就能实现我想要的效果。
这是我的查询:
router.get('/:pattern/:color/result', function(req, res, image){
console.log(req.params.color);
console.log(req.params.pattern);
Images.findAll({
where: {
pattern: req.params.pattern,
color: req.params.color
},
attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource', 'description_id']
}).then(function(image){
console.log(image.description_id);
//console.log(doc.descriptions_id);
res.render('pages/result.hbs', {
pattern : req.params.pattern,
color : req.params.color,
image : image
})
});
});
这是我的图像
模型:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'admin', 'pwd', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var Images = sequelize.define('images', {
pattern: {
type: Sequelize.STRING,
field: 'pattern'
},
color: {
type: Sequelize.STRING,
field: 'color'
},
imageUrl: {
type: Sequelize.STRING,
field: 'imageUrl'
},
imageSource: {
type: Sequelize.STRING,
field: 'imageSource'
},
description_id: {
type: Sequelize.INTEGER,
field: 'description_id'
}
});
module.exports = Images;
描述
型号:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'admin', 'pwd', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var Description = sequelize.define('description', {
color: {
type: Sequelize.STRING,
field: 'color'
},
body: {
type: Sequelize.STRING,
field: 'body'
}
});
module.exports = Description;
最佳答案
您需要为您的模型创建一些关联(请参阅 docs for defining associations )。然后,在您的查询中,您需要添加 include
选项(请参阅 docs about querying associations )。
关于mysql - Express - Sequelize - 在查询中添加外表字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192732/