如何从序列中的实例中排除“多对多关联”?

时间:2018-12-01 04:28:29

标签: database orm relational-database sequelize.js

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

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

这是输出:

enter image description here 无论如何,有没有避免不找回那个关联的方法?

2 个答案:

答案 0 :(得分:0)

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

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”,因此可以避免这种情况。即使代码看起来更优化,但无论如何,如果其他人有任何建议,我将不胜感激。

谢谢。

答案 1 :(得分:-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);
  }
]

希望对您有帮助。