【问题标题】:Renaming belongsToMany association with Sequalize用 Sequelize 重命名 belongsToMany 关联
【发布时间】:2019-11-23 15:38:48
【问题描述】:

鉴于此关联

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

以下模型已加载

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

如何将名称 ProductStock 更改为 stock

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    试试这段代码:

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

    【讨论】:

    • 这无济于事,我知道映射对象,但问题在于 Sequalize;当保存时存在别名时,它的行为很糟糕,并且来自through 表的支持记录要少得多。
    • @YanickRochon through: stock,只需在您的关联中进行此更改即可。
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多