我遇到了一个问题,我收到一个错误Unhandled rejection Error: description is not associated to images!
,我似乎无法弄清楚为什么我收到此错误。我在images
表中设置了一个外键,并认为我正在使用文档中标记的模型关联方法。理想情况下,我希望能够在查询图像时从描述模型中使用身体领域。Sequelize - 关联表和查询记录
表:
images
CREATE TABLE `images` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`pattern` varchar(225) DEFAULT NULL,
`color` varchar(225) DEFAULT NULL,
`imageUrl` varchar(225) DEFAULT NULL,
`imageSource` varchar(225) DEFAULT NULL,
`description_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `description_id` (`description_id`),
CONSTRAINT `images_ibfk_1` FOREIGN KEY (`description_id`) REFERENCES `description` (`description_id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;
description
CREATE TABLE `description` (
`description_id` int(11) NOT NULL,
`color` varchar(255) DEFAULT NULL,
`pattern` varchar(255) DEFAULT NULL,
`body` text,
PRIMARY KEY (`description_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
这里是我的两个型号:
imagesModel.js
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'
}
},{
classMethods: {
associate: function(models) {
Images.belongsTo(models.Description, {foreignKey: 'description_id'});
}
}
});
module.exports = Images;
descriptionModel.js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('db', 'admin', 'pwd', {
host: 'localhost',
port: 3306,
dialect: 'mysql'
});
var Images = require('./imagesModel');
var Description = sequelize.define('description', {
color: {
type: Sequelize.STRING,
field: 'color'
},
body: {
type: Sequelize.STRING,
field: 'body'
}
});
Description.hasMany(Images, {as: 'images'});
module.exports = Description;
这里是我的路线和查询:
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
},
include: [Description],
attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource', 'description_id']
}).then(function(image){
console.log(image.getDescription());
//console.log(doc.descriptions_id);
res.render('pages/result.hbs', {
pattern : req.params.pattern,
color : req.params.color,
image : image
})
});
});
我很感谢你的回答,看看我搞砸了试图使用两个表associ每种型号都有一个。我相反将您的方法应用于我的模型,但保留我的格式。我删除了'Description.hasMany(Images,{as:'images'}); '并将'description_id'字段添加到此模型中。这些似乎是您的答案中唯一的两个变化,我仍然收到此错误。我是否需要刷新或删除并重新上传我的数据到我的数据库?我是否缺少变化? – cphill
如果你保留你的格式,imagesModel.js中的关联类方法仍然可能没有被调用,这就是为什么你会看到这个错误。你真的应该改变你的代码和文件结构为我提到的两种模式之一,这样你的代码更具可读性。 –