gpt4 book ai didi

mysql - Express - Sequelize - 在查询中添加外表字段

转载 作者:行者123 更新时间:2023-11-29 21:55:28 27 4
gpt4 key购买 nike

我能够对我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com