在一个查询中创建一个包含联接数据的行,使用 Sequelize。

huangapple go评论49阅读模式
英文:

Creating a row with joined data in one query, sequelize

问题

我有两个表:ItemUser

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,并将其作为ItemuserId值传递。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.

huangapple
  • 本文由 发表于 2023年2月26日 19:31:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75571677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定