我遇到了一個問題,我收到一個錯誤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中的關聯類方法仍然可能沒有被調用,這就是爲什麼你會看到這個錯誤。你真的應該改變你的代碼和文件結構爲我提到的兩種模式之一,這樣你的代碼更具可讀性。 –