我有以下模特:
// User model
const User = sequelize.define('users_dev', {
id: {
type: Sequelize.UUID
primaryKey: true
},
fullName: {
type: Sequelize.STRING,
allowNull: false,
}
)}
// Game lobby model
const Lobby = sequelize.define('lobbies_dev', {
id: {
type: Sequelize.UUID,
primaryKey: true
},
player1: {
type: Sequelize.UUID // Need reference by user id
},
player2: {
type: Sequelize.UUID // Need reference by user id
}
)}
如何在lobby.player1(和2)与user.id之间创建关联?那么当我稍后向大厅提出请求时,我可以获得有关我的用户的信息吗?
我阅读了文档,尝试了很多选项,但只有6个小时的工作错误...
答案 0 :(得分:2)
要正确关联,您不必在Lobby模型中定义用户字段,而是必须关联它们:
// User model
const User = sequelize.define('user', { // note: changed the name
id: {
type: Sequelize.UUID
primaryKey: true
},
fullName: {
type: Sequelize.STRING,
allowNull: false,
}
)}
// Game lobby model
const Lobby = sequelize.define('lobby', { // note: changed the name
id: {
type: Sequelize.UUID,
primaryKey: true
}
})
// associate Users and Lobby
User.belongsTo(Lobby) // this will add 'lobbyId' attribute to User
然后,您可以create
或update
具有此关联的实例模型
示例:
const lobby = await Lobby.create({})
const player1 = await User.create({ fullName: 'a name', lobbyId: lobby.id})
这将允许您稍后加入:
const lobby = await Lobby.findById(id, { include: [{ model: User }] })
我还强烈建议将users_dev
和lobbies_dev
分别更改为user
和lobby
,因为Sequelize使用这些字符串来命名模型。