테이블 >> 로우와 컬럼으로 이루어져 있다.
comments 테이블 생성 워크밴치, 모델에서 만들어도 된다.
사용자 정보를 저장하는 테이블 생성 워크밴치, 모델에서 만들어도 된다.
id INT NOT NULL AUTO_INCREMENT
컬럼명 옆의 것들은 컬럼에 대한 옵션들
INT: 정수 자료형 (FLOAT, DOUBLE은 실수)
VARCHAR: 문자열 자료형, 가별 길이(CHAR은 고정 길이)
TEXT: 긴 문자열은 TEXT로 별도 저장
TINYINT: -128부터 127까지 저장, 1 or 0만 저장해 불 값으로 표현
NOT NULL: 빈 값은 받지 않음 (NULL은 빈값 허용)
AUTO_INCREMENT: 숫자 자료형인 경우 다음 로우가 저장될 때 자동으로 1 증가한다
UNSIGNED: 0과 양수만 허용
ZEROFILL: 숫자의 자리수가 고정된 경우 빈 자리에 0을 넣음 (00013)
DEFAULT now(): 날짜 컬럼의 기본값을 현재 시간으로
comment: 테이블에 대한 보충 설명 (필수아님)
DEFAULT CHARSET: utf8로 설정해야 한글이 입력된다. (utf8mb4하면 이모티콘까지 가능하다.)
ENGIN: InnoDB 사용
Primary Key(id)
id가 테이블에서 로우를 특정할 수 있게 해주는 고유한 값임을 의미한다
UNIQUE INDEX name_UNIQUE (name ASC)
해당 컬럼이 고유해야 함을 나타내는 옵션으로 name_UNIQUE는 옵션의 이름(아무렇게나 지어도 된다), ASC는 인덱스를 오름차순으로 저장함을 의미 내림차순은 DESC.
확인
mysql> DESC users;
삭제하기
mysql> DROP TABLE users;
댓글 테이블은 사용자 테이블과 관계가 있다.
SQL 작업을 쉽게 할 수 있도록 도와주는 라이브러리
ORM: Object Relational Mapping: 객체와 데이터를 매핑 (1:1)
MySQL 외에도 다른 RDB(Maria, PostGre, SQLite, MSSQL)와도 호환됨
자바스크립트 문법으로 데이터베이스 조작 가능
user에 대한 시퀄라이즈 모델
첫번쨰 파라미터는 컬럼에 대한 정의
두번째 파라미터는 모델에 대한 설정
// user.js
const Sequelize = require('sequelize');
class User extends Sequelize.Model {
static initiate(sequelize) {
User.init({
name: {
type: Sequelize.STRING(20),
allowNull: false,
unique: true,
},
age: {
type: Sequelize.INTEGER.UNSIGNED,
allowNull: false,
},
married: {
type: Sequelize.BOOLEAN,
allowNull: false,
},
comment: {
type: Sequelize.TEXT,
allowNull: true,
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
},
}, {
sequelize,
timestamps: false,
underscored: false,
modelName: 'User',
tableName: 'users',
paranoid: false,
charset: 'utf8',
collate: 'utf8_general_ci',
});
}
static associate(db) {
db.User.hasMany(db.Comment,
{ foreignKey: 'commenter', sourceKey: 'id' });
}
};
module.exports = User;
timestamps: createdAt, updatedAt 생성
paranoid: true면 deletedAt 생성 soft delete
underscored: 캐멀케이스로 생성되는 컬럼을 스네이크케이스로 생성
modelName: 모델 이름, tableName: 테이블 이름 설정
연결
// index.js
const Sequelize = require('sequelize');
const User = require('./user');
const sequelize = new Sequelize(config.database,
config.username, config.password, config);
db.sequelize = sequelize;
db.User = User;
User.init(sequelize);
User.associate(db);
module.exports = db;
users 모델과 comments 모델 간의 관계를 정의했다.
한명의 사용자가 여러개의 댓글을 작성하였다.
시퀄라이즈에서는 1:N관계를 hasMany로 표현한다. 반대의 입장은 belongTo이다.
belongTo가 있는 테이블에 컬럼이 생긴다.
// ...
static associate(db) {
db.user.hasMany(db.Comment,
{ foreignKey: 'commenter', sourceKey: 'id' })
}
user has many comment
comment의 commenter라는 컬럼이 내 id를 참조하고 있다.
(foreignKey: 너, sourceKey: 나)
// ...
static associate(db) {
db.Comment.belongTo(db.User,
{ foreignKey: 'commenter', targetKey: 'id' })
}
Comment belong to User
foreignKey(commenter)는 belongTo에 들어간다.
(foreignKey: 남의 키)
누가 hasOne 이고 누가 belongTo 인지는 개발자가 정해놔야 한다.
아래와 같이 작성한다면, Info에 UserId 컬럼이 생길 것이다.
db.User.hasOne(db.Info, {foreignKey: 'UserId', sourceKey: 'id'})
db.Info.belongTo(db.User, {foreignKey: 'UserId', targetKey: 'id'})
예) 게시글과 해시태그 테이블
DB 특성상 다대다 관계는 중간 테이블이 생긴다.
db.Post.belongsToMany(db.HashTag, {through: 'PostHasgtag'})
db.HashTag.belongsToMany(db.Post, {through: 'PostHasgtag'})
위에는 SQL문, 아래는 시퀄라이즈 쿼리(자바스크립트)
INSERT INTO node.js users (name, age, married, comment) VALUES ('zero', 24, 0, '자기소개1');
const {User} = require('../models');
User.create({
name: 'zero',
age: 24,
married: false,
comment: '자기소개1',
})
SELECT * FROM nodejs.users;
User.finALL({});
SELECT name, married FROM nodejs.users;
User.findALL({
attributes: ['name', 'married'],
})
특수한 경우 Sequelize.Op 연산자를 사용한다. (gt, or 등등..)
SELECT name, age FROM nodejs.users WHERE married = 1 AND age > 30;
const {Op} = require('sequelize');
const {User} = require('../models');
User.findAll({
attributes: ['name', 'age'],
where: {married: 1, age: {[Op.gt] : 30}},
});
SELECT id, name FROM users WHERE married = 0 OR age > 30
const {Op} = require('sequelize');
const {User} = require('../models');
User.findAll({
attributes: ['id', 'age'],
where: {[Op.or] : [{married: 0}, {age: {[Op.gt]: 30} }]
},
});
SELECT id, name FROM users ORDER BY age DECS;
User.findAll({
attributes: ['id', 'name'],
order: [['age', 'DESC']],
});
SELCET id, name FROM users ORDER BY age DESC LIMIT 1;
User.findAll({
attributes: ['id', 'name'],
order: [['age', 'DESC']],
limit: 1,
});
SELECT id, name FROM users ORDER BY age DESC LIMIT 1 OFFSET 1
User.findAll({
attributes: ['id', 'name'],
order: [['age', 'DESC']],
limit: 1,
offset: 1,
});
UPDATE nodejs.users SET comment = '바꿀내용' WHERE id = 2;
User.update({
comment: '바꿀내용'
}, {
where: {id: 2},
})
DELETE FROM nodejs.users WHERE id = 2;
User.destroy({
where: {id: 2}
})