【问题标题】:How to exclude association belongs-to-many from an instance in sequelize?如何从sequelize中的实例中排除关联属于多?
【发布时间】:2018-12-01 04:28:28
【问题描述】:

我正在尝试从具有模型关联的查询中排除联结模型,这就是它们的关联方式:

Warehouse.associate = function(models) {
  Warehouse.Products = Warehouse.belongsToMany(models.Product, {
    as: {
      singular: 'product',
      plural: 'products',
    },
    through: models.WarehouseProducts,
    foreignKey: "warehouse_id",
    otherKey: "product_id",
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE'
  });
}

Product.associate = function(models) {
  Product.Warehouses = Product.belongsToMany(models.Warehouse, {
    as: {
      singular: "warehouse",
      plural: "warehouses"
    },
    through: models.WarehouseProducts,
    foreignKey: "product_id",
    otherKey: "warehouse_id",
    onDelete: 'CASCADE',
    onUpdate: 'CASCADE'
  });
}

这是我用来检索仓库产品的代码:

export const prefetchWarehouse =  [
  validator.params.warehouse,
  async function(req, res, next) {
    try {
      if (validator.errors(req)) {
        throw validator.stack;
      } else {
        req.warehouse = await Warehouse.findById(req.params.warehouse);
        next();
      }
    } catch (err) {
      next(err);
    }
  }
];

export const getProduct = [
  validator.params.product,
  async function(req, res, next) {
    const result = await req.warehouse.getProducts({
      where: {
        id: {
          [Op.eq]: req.params.product
        }
      },
      plain: true
    });
    console.log('===>', result);
  }
]

这是输出:

有什么办法可以避免无法恢复这种关联吗?

【问题讨论】:

标签: database orm relational-database sequelize.js


【解决方案1】:

我遇到过这种行为,我通过将joinTableAttributes 设置为一个空数组(如joinTableAttributes: [])来解决它。

export const getProduct = [
  validator.params.product,
  async function(req, res, next) {
    const result = await req.warehouse.getProducts({
      joinTableAttributes: [], // Here
      where: {
        id: {
          [Op.eq]: req.params.product
        }
      },
      plain: true
    });
    console.log('===>', result);
  }
]

希望对你有所帮助。

【讨论】:

  • 谢谢 Mohdule,实际上这就是我一直在寻找的,它以同样的方式解决了我的问题 :)
【解决方案2】:

解决这个问题的一种方法是在我的处理程序中使用联结模型来避免它:

export function WarehouseProducts(WarehouseProducts) {
  WarehouseProducts.associate = function(models) {
    WarehouseProducts.Products = WarehouseProducts.belongsTo(models.Product, {
      as: "product"
    });
  };
}

然后在处理程序中:

const result = await WarehouseProducts.findOne({
  where: {
    warehouse_id: { [Op.eq]: req.params.warehouse },
    product_id: { [Op.eq]: req.params.product }
  },
  include: [ "product" ]
});

res.json(result.product);

虽然,按照我正在寻找的方式做会很好,因为相同的函数“prefetchWarehouse”在其他端点中被重用,所以这将有助于避免。尽管代码看起来更优化,但无论如何,如果其他人有任何建议,我将不胜感激。

谢谢。

【讨论】:

  • 另一种解决这个问题的方法是使用来自 sequelize 的原始查询,这就是我所做的,现在我的查询非常干净/安全并且非常好。
猜你喜欢
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2020-10-11
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多