INNER JOIN запрос в Sequelize
Как выполнить этот запрос в 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 шт):
Автор решения: Anatoly
→ Ссылка
Как минимум добавить ассоциацию между моделями:
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: []
}]
})