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

标签 mysql node.js express sequelize.js

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

相关文章:

绘制ER图的Java图形二维库?

javascript - 尝试使用express-load和express 4

node.js - react 应用程序 : Using Node/express as middle-end proxy server

php - 返回错误 mysqli_query() expects parameter 1 to be mysqli, null given for steam login

php - 如何在我的 MySQL 表的列中找到最常见的结果

javascript - 永远在后台运行peerjs服务器

javascript - 运行 npm start 时启动脚本丢失错误

node.js - 从不同位置提供图像和js ExpressJs : Node

mysql - 我如何将这些查询放入一个查询中?

Mysql 和 NodeJS 无法远程连接到已部署的应用程序