简体   繁体   English

使用 M:N 续集创建/发布

[英]Sequelize Create/Post with M:N

I am trying to implement a M:N Association with Sequelize.我正在尝试使用 Sequelize 实现 M:N 关联。 For this I took a look at the documentation ( doc ) and found something very similar to my use case:为此,我查看了文档( doc ),发现与我的用例非常相似:

User.belongsToMany(Profile, { through: User_Profile });
Profile.belongsToMany(User, { through: User_Profile });

Now I would like to have an endpoint, which allows me to add a new User with a list of existing Profiles.现在我想要一个端点,它允许我添加一个包含现有配置文件列表的用户。 (Or the other way around). (或相反)。 So eg { "id": 4, "username": "p4dm3" "profiles": [ { "id": 6 }, { "id":4 ] }例如 { "id": 4, "username": "p4dm3" "profiles": [ { "id": 6 }, { "id":4 ] }

However, as far as I can tell, the documentation only mentions the case of not existing Profiles with the include statement.但是,据我所知,文档只提到了包含语句不存在 Profiles 的情况。 Of course I could first create a new user and in the next step create the associations, but I think for transaction handling it would me more convenient to do this in one step.当然,我可以先创建一个新用户,然后在下一步创建关联,但我认为对于事务处理,一步完成会更方便。 Furthermore, my issue is very similar to the one described here .此外,我的问题与此处描述的问题非常相似。 Thanks in advance.提前致谢。

If you have no user, you'll have to create that first and then you can save the existing profiles to it with a sequelize helper:如果您没有用户,则必须先创建该用户,然后您可以使用 sequelize 助手将现有配置文件保存到其中:

const profiles = [profiles]
const user = await User.create(req.body)
user.addProfiles(profiles)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM