1

Как выполнить этот запрос в Sequelize?

SELECT features.name 
FROM typeFeatures
INNER JOIN features ON featuresId = features.id

Models:

const Feature = sequelize.define('feature', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
    name: { type: DataTypes.STRING, allowNull: false }
});

const TypeFeature = sequelize.define('typeFeature', {
    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }
});

Т.е. чтобы вместо:

{
    "id": 1,
    "featureId": 1
}

Получить это:

{
    "id": 1,
    "feature.name": "TestName"
}

1 ответ 1

1

Как минимум добавить ассоциацию между моделями:

TypeFeature.belongsTo(Feature, { foreignKey: 'featuresId' })

А потом сделать запрос TypeFeature и включить заассоциированную модель Feature (см. запросы с ассоциациями):

const typefeature = await TypeFeature.findByPk(1, {
  include: [{
    model: Feature,
    attributes: ['name']
  }]
})

Тогда в typefeature будет:

{
    "id": 1,
    "feature": {
      "name": "TestName"
    }
}

Если прям надо без вложенного объекта просто на уровне полей основной модели получить name, то так:

const typefeature = await TypeFeature.findByPk(1, {
  attributes: ['id', [['feature', 'name'], 'feature.name']],
  include: [{
    model: Feature,
    attributes: []
  }]
})
1
  • Спасибо за подробное объяснение
    – Alexei
    15 дек 2021 в 4:49

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.