如何在Sequelize Postgresql中执行多个内部联接

时间:2017-10-03 18:24:51

标签: node.js postgresql join sequelize.js

RDBMS和Sequelize的新手也希望在JOINS中获得更多内容。我不知道如何通过SEQUELIZE执行JOINS。我有3个表USERS,ORDERS,PRODUCTS ORDERS表包含USERS,PRODUCTS主键作为其外键。我在下面附上我的型号代码 用户模型

const Sequelize = require('sequelize');
const sequelize = require('../config');
let Users = sequelize.define('users', {
  id : {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  username: {
    type: Sequelize.STRING,
  },
  password: {
    type: Sequelize.STRING
  }
});
module.exports = Users;

产品型号

const Sequelize = require('sequelize');
const sequelize = require('../config');
let products=sequelize.define('products', {
  id : {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  category : {
    type: Sequelize.STRING,
    allowNull: false
  },
  name : {
    type: Sequelize.STRING,
    allowNull: false
  },
  price: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
});
module.exports= products;

订单模型

const Sequelize = require('sequelize');
const sequelize = require('../config');
let users=require('./user');
let products=require('./product');
let orders=sequelize.define('orders', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: Sequelize.INTEGER,
    references: {
        model: 'users',
        key: 'id'
    }
  },
  product_id: {
    type: Sequelize.INTEGER,
    references: {
        model: 'products',
        key: 'id'
    }
  },
  price: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
});
module.exports= orders;

我希望通过SEQUELIZE

执行以下原始查询
SELECT * FROM ((orders INNER JOIN users ON users.id=orders.user_id) INNER JOIN products ON products.id=orders.product_id);

我查看了文档,但我无法弄清楚如何做到这一点。非常感谢。谢谢

2 个答案:

答案 0 :(得分:1)

您需要做的第一件事就是设置Associations

所以让我们把它分解成部分。我们知道您的ORDERS表包含USER和PRODUCT的ID。这就是为这些表设置关联的方法。

  1. 我假设用户有很多订单。我们在两个方向上建立联系。

    User.hasMany(Orders,{foreignKey:'user_id'}); Order.belongsTo(User,{foreignKey:'user_id'});

  2. 您似乎正确定义了模型。

    1. 现在为了进行连接,在设置关联之后,我们想要设置一个查询来为表做连接。现在请记住,这将在您的控制器中完成。
    2. //确保您在此处导入模型以使用

      export function getRequestsByWeek(req, res) {
        return order.findAll({
          include: [
            {model: users, attributes: []}, // nothing in attributes here in order to not import columns from users
            {model: products} // nothing in attributes here in order to not import columns from products
          ],
          attributes: ['id'], //in quotes specify what columns you want, otherwise you will pull them all
          // Otherwise remove attributes above this line to import everything. 
        })
          .then(respondWithResult(res))
          .catch(handleError(res));
      }
      

答案 1 :(得分:0)

update