My Sequelize Notes
It's been 1 years since i'm into NodeJS, and sequelize is my favorite ORM to works with database.
1.After create a new Row, you want to get the ID of the data, you must make some changes in the model, and add this.
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
2.If your current server timezone is not the same as your timezone, but you want to get the datetime fields using your specified timezone, you can use this (i'm using day.js), so don't forget to import the library first.
const moment = require('dayjs');
const utc = require('dayjs/plugin/utc')
dateTime:{
type: DataTypes.DATE,
get() {
const rawValue = this.getDataValue('dateTime');
// parse raw value using whatever logic you want
// this won't work, but you get the idea
return moment(rawValue).utc().format('YYYY-MM-DD HH:mm:ss');
}
},
3.Associations - HasOne
This is almost the same as
belongsTo
with one exception - The foreign key will be defined on the target model.
So the Example Table:
Person
-id
-name
-createdAt
-modifiedAt
Identity
-id
-name
-createdAt
-modifiedAt
-personId*
The code example is:
Person.hasOne(Identity, {
foreignKey: 'personId'
});
To Get the Identity, you can use this code:
person.getIdentity();
Has is a property, Belogs is more like a relation.
4.Associations - BelongsTo
So the Example Table:
Person
-id
-name
-createdAt
-modifiedAt
Identity
-id
-name
-createdAt
-modifiedAt
-personId*
The code example is:
Identity.belongsTo(Person, {
});
To Get the Identity, you can use this code:
person.getIdentity();
References:
Manual | Sequelize
https://sequelize.org/master/manual/model-basics.html
Manual | Sequelize
https://sequelize.org/v5/manual/models-definition.html
Manual | Sequelize
https://sequelize.org/master/manual/migrations.html
Sequelize BelongsTo & HasMany Associations - Edward Timmer - Medium
https://medium.com/@edtimmer/sequelize-associations-basics-bde90c0deeaa
Sequelize relationships — Ultimate guide - David MARIE - Medium
https://medium.com/@eth3rnit3/sequelize-relationships-ultimate-guide-f26801a75554
How to define Sequelize associations using migrations
https://medium.com/@andrewoons/how-to-define-sequelize-associations-using-migrations-de4333bf75a7
Sequelizeを使用してデータベースを操作するための基本的な情報 - Qiita
https://qiita.com/mima_ita/items/014dcb42872f3a10855b
Node.js, Express, sequelize, React で始めるモダン WEB アプリケーション入門(Express/sequelize編) - Qiita
https://qiita.com/tatsurou313/items/2ba0387806b07f442b8c
ruby on rails - What's the difference between belongs_to and has_one? - Stack Overflow
https://stackoverflow.com/questions/3808926/whats-the-difference-between-belongs-to-and-has-one
Ruby on Rails : Has_One versus Belongs_To
http://duanesbrain.blogspot.com/2006/05/ruby-on-rails-hasone-versus-belongsto.html
Database Associations- "Has One" vs "Belongs To" - In Lehman's Terms
http://inlehmansterms.net/2014/07/28/has_one-vs-belongs_to/