Skip to content

Instantly share code, notes, and snippets.

@andrewjmead
Last active January 5, 2020 20:54
Show Gist options
  • Save andrewjmead/f2a11ac7d028d3dd180c to your computer and use it in GitHub Desktop.
Save andrewjmead/f2a11ac7d028d3dd180c to your computer and use it in GitHub Desktop.
Sequelize One-To-One Relationship
var Sequelize = require('sequelize');
var sequelize = new Sequelize(undefined, undefined, undefined, {
'dialect': 'sqlite',
'storage': __dirname + '/basic-sqlite-database.sqlite'
});
var Profile = sequelize.define('profile', {
someData: Sequelize.STRING
});
var User = sequelize.define('user', {
email: Sequelize.STRING
});
Profile.belongsTo(User);
User.hasOne(Profile);
sequelize.sync({
force: true
}).then(function() {
var user;
User.create({
email: 'andrew@example.com'
}).then(function(u) {
user = u;
return Profile.create({
someData: 'data here'
});
}).then(function(profile) {
user.setProfile(profile)
})
});
@shepelevstas
Copy link

shepelevstas commented Sep 9, 2018

Isn't both Profile.belongsTo(User); and User.hasOne(Profile); add userId to Profile model and nothing to User model?

@JefferyHus
Copy link

Exactly, and that's why this is stupid, my head is heated because both belongsTo and hasOne adds the foreignkey to Profile table and nothing to user, this is ridiculous

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment