英文:
Creating a row with joined data in one query, sequelize
问题
我有两个表:Item 和 User。
export const Item = sequelize.define('item', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING, allowNull: false, unique: true}
})
export const User = sequelize.define('user', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
email: {type: DataTypes.STRING, allowNull: false, unique: true}
})
它们之间有关联关系:
User.hasOne(Item)
Item.belongsTo(User)
我希望 sequelize 在 item 表中创建一行记录,但我只有 user 的电子邮件。我能否传递电子邮件而不是 userId,并在一次查询中创建一个项目,而不使用 User.findOne?
我还没有尝试过任何方法。
英文:
I have two tables: Item and User.
export const Item = sequelize.define('item', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
name: {type: DataTypes.STRING, allowNull: false, unique: true}
})
export const User = sequelize.define('user', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
email: {type: DataTypes.STRING, allowNull: false, unique: true}
})
They are associated:
User.hasOne(Item)
Item.belongsTo(User)
I want sequelize to create a row in the item table, but i have only email of user. Can i pass the email instead of userId and create an item in one query without User.findOne?
I didn't try anything yet
答案1
得分: 0
你应该知道一个用户的ID,该用户应该被喜欢到一个新的item记录中,因此您需要在手头上以某种方式拥有用户ID,并将其作为Item的userId值传递。Item关联对用户的电子邮件一无所知。唯一的方式是在创建Item记录的同时创建用户,这样您才能拥有用户的电子邮件。
英文:
You should know an id of a user that should be liked to a new item record so you need to have a user id one way or another on your hands and pass it as userId value of Item. The Item association knows nothing about user's email.
The only way you can have only user's email while creating an Item record is when you're crating a user along with an item.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论