如何在Sequelize中从一个实例中排除关联属于多个? [英] How to exclude association belongs-to-many from an instance in sequelize?

查看:0
本文介绍了如何在Sequelize中从一个实例中排除关联属于多个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从与模型关联的查询中排除交叉点模型,它们的关联方式如下:

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);
  }
]

以下是输出:

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

推荐答案

我遇到过这种行为,我只需将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);
  }
]

希望这对您有帮助。

这篇关于如何在Sequelize中从一个实例中排除关联属于多个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆