Created
September 29, 2016 15:15
-
-
Save AloofBuddha/d27e35313acfcaec39fae92f6ff3c362 to your computer and use it in GitHub Desktop.
An explanation of how to define a One-to-One relationship in Sequelize and different ways of create the linked objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Product Model definition, called 'product' and associated with table 'products' | |
var Product = this.sequelize.define('product', { | |
title: Sequelize.STRING | |
}); | |
// User Model definition, called 'user' and associated with table 'users' | |
var User = this.sequelize.define('user', { | |
first_name: Sequelize.STRING, | |
last_name: Sequelize.STRING | |
}); | |
// creates a 'userId' field in the Product model | |
Product.belongsTo(User); | |
// long way | |
//create a new User, saves it to the DB | |
User.create({ | |
first_name: 'Mick', | |
last_name: 'Broadstone' | |
}) | |
.then(user => { | |
// once user is created, create a product, and fill in the userId field manually | |
Product.create({ | |
title: 'Chair', | |
userId: user.id | |
}) | |
}) | |
// nicer way | |
Product.create({ | |
title: 'Desk', | |
// provide a 'user' field where you provide a user definition | |
user: { | |
first_name: 'Ben', | |
last_name: 'Cohen' | |
} | |
}, { | |
include: [ User ] // include a data dependency | |
}); | |
// Product is created, but before it can fill in userId it creates a new User | |
// with the provided data and automatically adds that user.id value into the Products | |
// userId column | |
// Note that both ways are really equivalent, so neither is truly nicer, its | |
// a matter of choice | |
/*-------------------------- The Database ---------------------------* | |
| ------------- | | |
| | | |
| products | users | | |
| -------- | ------ | | |
| id title userId | id first_name last_name | | |
| -- ----- ------ | -- ---------- --------- | | |
| 44 'Chair' 12 | 12 'Mick' 'Boradstone' | | |
| 56 'Desk' 32 | 32 'Ben' 'Cohen' | | |
| | | | |
| | | | |
*-------------------------------------------------------------------*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment