我正在使用sequelize ORM;一切都很好,很干净,但是当我将其与join查询一起使用时遇到了问题。我有两种模式:用户和帖子。
join
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而不是从两个表中进行选择,但是结果应该是相同的
进一步阅读: