我是Sequelize的新人,我一直在浪費時間只是一個簡單的查詢。 sequelize的聯合使我的頭旋轉@@。Sequelize JS - 如何使用複合鍵進行多重連接查詢?
所以我想運行此查詢
SELECT a.first_name, a.last_name, b.host_id FROM RoomDetails a
LEFT JOIN Rooms b ON b.host_id = a.chat_id
LEFT JOIN States c ON c.id = b.state_id
WHERE c.bot='$bot_name' AND c.chat_id='$chatid';
我不知道如何實現sequelize格式的方式。 這裏是我的模型:
states.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var states = sequelize.define('states', {
botName: DataTypes.STRING,
chatId: DataTypes.INTEGER,
state: DataTypes.STRING,
turnId: DataTypes.INTEGER,
turnName: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
states.hasOne(models.rooms, {
as: 'rooms',
foreignKey: {
name: 'stateId'
},
foreignKeyConstraint: true
});
// associations can be defined here
}
}
});
return states;
};
rooms.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var rooms = sequelize.define('rooms', {
stateId: DataTypes.INTEGER,
hostId: DataTypes.INTEGER,
maxLetter: DataTypes.INTEGER
}, {
classMethods: {
associate: function(models) {
rooms.belongsTo(models.states, {
as: 'states',
foreignKey: {
name: 'stateId'
},
foreignKeyConstraint: true
});
rooms.hasMany(models.roomdetails, {
as: 'roomdetails',
foreignKey: {
name: 'roomId'
},
foreignKeyConstraint: true
});
rooms.belongsToMany(models.roomdetails, {
as: 'roomdetailschatid',
foreignKey: {
name: 'hostId'
},
foreignKeyConstraint: true
});
// associations can be defined here
}
}
});
return rooms;
};
roomdetails.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var roomdetails = sequelize.define('roomdetails', {
roomId: DataTypes.INTEGER,
chatId: DataTypes.INTEGER,
firstName: DataTypes.STRING,
lastName: DataTypes.STRING
}, {
classMethods: {
associate: function(models) {
roomdetails.belongsTo(models.rooms, {
as: 'rooms',
foreignKey: {
name: 'roomId'
},
foreignKeyConstraint: true
});
roomdetails.belongsTo(models.rooms, {
as: 'roomshostid',
foreignKey: {
name: 'chatId'
},
foreignKeyConstraint: true
});
// associations can be defined here
}
}
});
return roomdetails;
};
這就是我一直在努力,到目前爲止
module.exports.getHostInfo = function(res) {
return models.roomdetails.findOne({
include: {
required: true,
model: models.rooms,
as: 'rooms',
include: {
required: true,
model: models.states,
as: 'states',
where: {
botName: { $eq: general.botName },
chatId: { $eq: res.chat.id },
state: { $ne: general.FINISHED}
}
}
}
})
.then(function (response) {
console.log(response);
return response;
})
.catch(function (error) {
console.log('error getTotalPlayer', error);
});
}
,它總是返回錯誤,如未知列在「字段列表」
任何機構可以幫助我「rooms.roomdetailId」? 任何幫助將不勝感激,謝謝