ar 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); })
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`;
如果要查找具有用户的所有帖子,其中SQL将如下所示:
SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id
这在语义上与OP的原始SQL相同:
SELECT * FROM posts, users WHERE posts.user_id = users.id
那就是你想要的:
Posts.findAll({ include: [{ model: User, required: true }] }).then(posts => { /* ... */ });
设置为true是设置内部联接的关键。如果你想要一个左外连接,然后将所需更改为false,或将其保持关闭,因为这是默认值:
Posts.findAll({ include: [{ model: User, // required: false }] }).then(posts => { /* ... */ });
如果要查找属于出生年份为1984年的用户的所有帖子,你需要:
Posts.findAll({ include: [{ model: User, where: {year_birth: 1984} }] }).then(posts => { /* ... */ });
请注意,只要在其中添加where子句,默认情况下为true。
如果你想要所有帖子,无论是否有用户附加但是如果有用户,那么只有1984年出生的用户,那么请将所需的字段添加回来:
Posts.findAll({ include: [{ model: User, where: {year_birth: 1984} required: false, }] }).then(posts => { /* ... */ });
如果你想要名称为“Sunshine”的所有帖子,并且只有它属于1984年出生的用户,你可以这样做:
Posts.findAll({ where: {name: "Sunshine"}, include: [{ model: User, where: {year_birth: 1984} }] }).then(posts => { /* ... */ });
如果你想要名称为“Sunshine”的所有帖子,并且只有当它属于与帖子上的post_year属性匹配的同一年出生的用户时,你才会这样做:
Posts.findAll({ where: {name: "Sunshine"}, include: [{ model: User, where: ["year_birth = post_year"] }] }).then(posts => { /* ... */ });