mysql – 如何在nodejs中使用sequelize进行连接查询

我使用sequelize ORM;一切都伟大和干净,但我有一个问题,当我使用它与连接查询。
我有两个模型:用户和帖子。

var User = db.seq.define('User',{
    username: { type: db.Sequelize.STRING},
    email: { type: db.Sequelize.STRING},
    password: { type: db.Sequelize.STRING},
    sex : { type: db.Sequelize.INTEGER},
    day_birth: { type: db.Sequelize.INTEGER},
    month_birth: { type: db.Sequelize.INTEGER},
    year_birth: { type: db.Sequelize.INTEGER}

});

User.sync().success(function(){
    console.log("table created")
}).error(function(error){
    console.log(err);
})


var Post = db.seq.define("Post",{
    body: { type: db.Sequelize.TEXT },
    user_id: { type: db.Sequelize.INTEGER},
    likes: { type: db.Sequelize.INTEGER, defaultValue: 0 },

});

Post.sync().success(function(){
    console.log("table created")
}).error(function(error){
    console.log(err);
})

我想要一个查询,响应与一个帖子与用户的信息,使它。在原始查询中,我得到这个:

db.seq.query('SELECT * FROM posts, users WHERE posts.user_id = users.id ').success(function(rows){
            res.json(rows);
        });

我的问题是我如何可以更改代码使用ORM风格而不是SQL查询?

最佳答案
User.hasMany(Post, {foreignKey: 'user_id'})
Post.belongsTo(User, {foreignKey: 'user_id'})

Post.find({ where: { ...}, include: [User]})

哪个会给你

SELECT `posts`.*, `users`.`username` AS `users.username`, `users`.`email` AS `users.email`, `users`.`password` AS `users.password`, `users`.`sex` AS `users.sex`, `users`.`day_birth` AS `users.day_birth`, `users`.`month_birth` AS `users.month_birth`, `users`.`year_birth` AS `users.year_birth`, `users`.`id` AS `users.id`, `users`.`createdAt` AS `users.createdAt`, `users`.`updatedAt` AS `users.updatedAt` FROM `posts` LEFT OUTER JOIN `users` AS `users` ON `users`.`id` = `posts`.`user_id`;

上面的查询看起来可能比你发布的有点复杂,但是它的作用基本上只是对用户表的所有列进行别名,以确保它们在返回时放置到正确的模型中,而不与帖子模型混淆

除此之外,你会注意到它做一个JOIN而不是从两个表中选择,但结果应该是相同的

进一步阅读:

> http://docs.sequelizejs.com/en/latest/docs/associations/#one-to-one-associations
> http://docs.sequelizejs.com/en/latest/docs/associations/#one-to-many-associations
> http://docs.sequelizejs.com/en/latest/docs/models-usage/#eager-loading

转载注明原文:mysql – 如何在nodejs中使用sequelize进行连接查询 - 代码日志