'How to add entrys in 1:1 model in sequelize?
I´ve followed official documentation and much of web posts for build models and associations in sequelize.
I´ve created 2 models, user and key (passwords).
I´ve created a: Key.belongsTo(User, {foreignKey: 'userId'}) association.
Well, when I launch the app, sequelize.sync() creates tables correctly, and creates a Keys table which has these fields:
id (PK) // key (string) // createdAt // updatedAt // userId (FK)
It seems all is correct but I've been stuck for a few days here, I want to use this model in user-controller.js where I want create an entry in the Users table that automatically create an entry in Keys table but, when I do something like below, nothing happens in the Keys table:
let newUser = await User.build({
name: params.name,
surname: params.surname,
nick: params.nick,
email: params.email,
key: params.password
})
let insertUser = await newUser.save();
Obviously, I'm using brcrypt in the original code.
If I try to trick the entry and I do something like:
let newIdUserEntry = insertUser.id;
let newKey = await Key.build({
key: hashPass,
userId: newIdUserEntry
})
newKey.save();
The entry in Keys table, has a null in userId.
Solution 1:[1]
In case it helps other people, this is the code I finally implemented:
// Models
let User = require('../models/user')(sequelize, Sequelize);
let Key = require('../models/key')(sequelize, Sequelize);
// Associations
User.hasOne(Key, {foreignKey: 'userId'});
Key.belongsTo(User, {foreignKey: 'userId'});
User.hasMany(Friend, {foreignKey: 'IDtarget'})
let newUser = await User.build({
name: params.name,
surname: params.surname,
nick: params.nick.toLowerCase(),
email: params.email.toLowerCase(),
Key: {
key: hashPass
},
image: null
},{
include: [{ model: Key}] //, through: 'userId'}]
})
Thanks for helping me!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tyler2P |
