简体   繁体   中英

Sequelize Create/Post with M:N

I am trying to implement a M:N Association with Sequelize. For this I took a look at the documentation ( doc ) and found something very similar to my use case:

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 ] }

However, as far as I can tell, the documentation only mentions the case of not existing Profiles with the include statement. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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