简体   繁体   English

用 Sequalize 重命名 belongsToMany 关联

[英]Renaming belongsToMany association with Sequalize

Given this assocation鉴于此关联

Product.Locations = Product.belongsToMany(ProductLocation, { 
   as: 'locations', 
   through: ProductStock,
   foreignKey: 'productId',
   otherKey: 'locationId'
});

The following model is loaded加载如下model

const product = await Product.findById(123, { include: Product.Locations });
console.log(product);
// -> {
//   id: 123,
//   ....,
//   locations: [ {
//      ProductStock: { productId: 123, locationId: 456, stock: 99 },
//      id: 456,
//      ...
//   } ],
//   ...
// }

How do I change the name ProductStock to stock ?如何将名称ProductStock更改为stock

Just try this code:试试这个代码:

    var str=
    {
      id: 123,
      locations: 
      [ 
        {
            ProductStock: { productId: 123, locationId: 456, stock: 99 },
            id: 456,
        },
      ],
    };
    var str2=
    {
      id:str.id,
      locations:
      [
        {
          stock:
          { 
            productId:str.locations[0].ProductStock.productId,
            locationId:str.locations[0].ProductStock.locationId,
            stock:str.locations[0].ProductStock.stock
          },
          id:str.locations[0].id
        }
      ]
    };
    console.log(JSON.stringify(str2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM