联接查询响应的格式

时间:2019-03-15 17:05:47

标签: node.js orm sequelize.js

我为Sequelize定义了以下模型

const brand = sequelize.define('brands', {
    brand_id: {
        type: Sequelize.UUID,
        primaryKey: true
    },
    name: Sequelize.STRING
}, {
    timestamps: false,
        underscored: true
});

const model = sequelize.define('models', {
    model_id: {
        type: Sequelize.UUID,
        primaryKey: true
    },
    name: Sequelize.STRING
}, {
    timestamps: false,
    underscored: true
});

model.belongsTo(brand, {foreignKey: 'brand_id'});

我使用此代码查询数据库

model.findOne({
    raw: true,
    where: {name: 'TIPO'},
    include: brand})
.then(car => {
    console.log(car);
});

它返回格式如下的行

{ model_id: '7e5a29ba-05b1-45f7-9fee-41f8440fe975',
  name: 'TIPO',
  brand_id: 'f3e4962c-906f-46c4-b992-7375ab46002a',
  'brand.brand_id': 'f3e4962c-906f-46c4-b992-7375ab46002a',
  'brand.name': 'FIAT' }

虽然我真的很想让它看起来像这样

{ model_id: '7e5a29ba-05b1-45f7-9fee-41f8440fe975',
  model_name: 'TIPO',
  brand_name: 'FIAT' }

有没有办法让它像这样工作?

2 个答案:

答案 0 :(得分:1)

您需要使用属性选项

model.findOne({
    raw: true,
    where: {name: 'TIPO'},
    include: {
      model: model.brand,
      attributes: [ 'name' ], // represents brand.name
      }
    })
.then(car => {
    const newCar = car;
    // if you want to change/rename the object properties around, do so here via newCar
    console.log(newCar);
});

您可能需要考虑将品牌模型中的“名称”更改为bName或brandName以避免混淆。

答案 1 :(得分:0)

您需要同时向模型和品牌添加属性...如果没有这些属性,您将看到所有字段(例如SELECT *)。看看doc