【问题标题】:How can i turn my query into an sequelize query?我怎样才能把我的查询变成一个续集查询?
【发布时间】:2021-06-02 17:49:57
【问题描述】:

我有一个查询需要转换为 ORM Sequelize(使用 MySQL 作为 DB)

select departments.name_department, products.name, products.descricao, products.disponivel, products.destaque, produts.estoque
from products
inner join departments
on id_dep = departments.id
where id_dep = req.params

试过了

async productByDep(req,res){
    const {id} = req.params;
    Departments.hasMany(Product, {foreignKey: 'id_dep'})
    Product.belongsTo(Department)
    Product.findAll({where: {id_dep : id}})
}

但我得到的查询与第一个完全不同。

【问题讨论】:

    标签: mysql node.js sequelize.js crud


    【解决方案1】:

    我终于找到了方法;

    我用过:

    async productByDep(req, res) {
    const { id } = req.params;
    const products_dep = await Department.findAll({
      attributes: ['name_department'],
      include: [{
        model: Product,
        where: { id_dep: id },
        attributes: ['name', 'descricao','preco','estoque']
      }]
    })
    return res.json(products_dep)
    

    }

    【讨论】:

      【解决方案2】:

      您确实无法控制 Sequelize 形成的确切 SQL 查询。
      ORM 的主要目的是让您无需考虑底层 SQL 查询即可获得所需的数据。

      相反,你

      1. 定义模型。
      2. 指定这些模型之间的关联。
      3. 当您想要执行连接时,只需添加include 子句。

      在编写 Sequelize 查询时,您只需考虑您想要什么数据。您不必考虑 SQL 查询。
      如果您正确定义了关联,您肯定会得到正确的数据。
      查看Eager Loading 上的 Sequelize 文档。

      在您的特定情况下,将有两个模型 - DepartmentsProducts

      const sequelize = require('sequelize');
      
      // Define the models
      const Departments = sequelize.define('Departments', {
        id: { type: sequelize.DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        departmentName: DataTypes.STRING,
      });
      
      const Products = sequelize.define('Products', {
        id: { type: sequelize.DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        name: sequelize.DataTypes.STRING,
        id_dep: {
          type: sequelize.DataTypes.INTEGER,
          references: {
            model: 'Departments',
            key: 'id',
          }
        }
      });
      
      // Define the associations between the models
      // i.e. how the different models are related to each other
      Departments.hasMany(Product, { foreignKey: 'id_dep' });
      Product.belongsTo(Department);
      
      // Query the data
      Product.findAll({
        where: { id: req.params.id },
        include: Departments
      });
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-28
        • 2021-08-01
        • 1970-01-01
        • 2021-07-31
        • 2013-08-29
        • 1970-01-01
        相关资源
        最近更新 更多