Sequelize:如何将 findAll 结果作为 Model.create 值传递
Sequelize: how to pass findAll result as Model.create value
我试图通过传递来自 table“用户”的 ID 将一个条目插入 table“消息”以用作条目值,但我得到一个“val.replace 不是函数错误”。这是我的代码:
Message.create({
userId:
Users.findAll({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
console.log(result.id)
return result.id
}),
roomname: 'lobby',
message: 'testing'
})
我的控制台日志返回了正确的 ID 号,但没有将该号码传递给“userId”。
要么使用 async/await 并首先找到用户然后创建一条消息,要么
在 then
回调中创建消息。
顺便问一下,您的 userId
是否包含用户 ID 数组?因为Users.findAll
returns一个对象数组。
第一个解决方案:
// here we get first user that satisfies our condition
const foundUser = await Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
})
await Message.create({
userId: foundUser.id,
roomname: 'lobby',
message: 'testing'
})
第二种方案
// here we get first user that satisfies our condition
Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
Message.create({
userId: result.id,
roomname: 'lobby',
message: 'testing'
})
})
确保您至少找到了一位用户,否则请检查该用户。
我试图通过传递来自 table“用户”的 ID 将一个条目插入 table“消息”以用作条目值,但我得到一个“val.replace 不是函数错误”。这是我的代码:
Message.create({
userId:
Users.findAll({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
console.log(result.id)
return result.id
}),
roomname: 'lobby',
message: 'testing'
})
我的控制台日志返回了正确的 ID 号,但没有将该号码传递给“userId”。
要么使用 async/await 并首先找到用户然后创建一条消息,要么
在 then
回调中创建消息。
顺便问一下,您的 userId
是否包含用户 ID 数组?因为Users.findAll
returns一个对象数组。
第一个解决方案:
// here we get first user that satisfies our condition
const foundUser = await Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
})
await Message.create({
userId: foundUser.id,
roomname: 'lobby',
message: 'testing'
})
第二种方案
// here we get first user that satisfies our condition
Users.findOne({
where: { username: "sam123" },
attributes: ['id'],
plain: true
}).then((result) => {
Message.create({
userId: result.id,
roomname: 'lobby',
message: 'testing'
})
})
确保您至少找到了一位用户,否则请检查该用户。