How to make join queries using Sequelize on Node.js

前端 未结 4 1478
情深已故
情深已故 2020-11-28 01:55

I am using sequelize ORM; everything is great and clean, but I had a problem when I use it with join queries. I have two models: users and posts.



        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 02:37

    User.hasMany(Post, {foreignKey: 'user_id'})
    Post.belongsTo(User, {foreignKey: 'user_id'})
    
    Post.find({ where: { ...}, include: [User]})
    

    Which will give you

    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`;
    

    The query above might look a bit complicated compared to what you posted, but what it does is basically just aliasing all columns of the users table to make sure they are placed into the correct model when returned and not mixed up with the posts model

    Other than that you'll notice that it does a JOIN instead of selecting from two tables, but the result should be the same

    Further reading:

    • 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

提交回复
热议问题