Sequelize query문(JS)

SQL문

INSERT INTO nodejs.users (name, age, married, comment) VALUES (’adam’, 29, 0, ‘자기소개1’)

Sequelize문

const { User } = require('./models').User;

// 메서드들은 다 promise이기 때문에 앞에 await이나 뒤에 then을 붙여줘야한다.
User.create({
  name: 'adam',
  age: 29,
  married: false,
  comment: '자기소개1',
})
  .then((result) => {
    console.log(result);
  })
  .catch((err) => {
    console.error(err);
  });
Select * FROM nodejs.users;

User.findAll({})
SELECT name, married FROM nodejs.users;

User.findAll({
	attributes: ['name', 'married']
})

관계 쿼리

const user = await User.findOne({
  include: [
    {
      model: Comment,
      where: {
        id: 1,
      },
      attributes: ['id'],
    },
  ],
});

유저 테이블에서 아이디가 1인 댓글을 찾음

  • model: Comment: User 모델과 조회할 Comment 모델 간의 관계를 지정

  • where: { id: 1 }: 조회할 Comment 모델의 id가 1인 데이터를 선택

  • attributes: ['id']: 조회 결과에서 Comment 모델의 id 컬럼만 선택

raw 쿼리

직접 SQL을 쓸 수 있음

const [result, metadata] = await Sequelize.query('SELECT * from comments')

Sequelize에서 CRUD

// Create
Model.create()

// Read
Model.findAll(), Model.findByPk(), Model.findOne()

// Update
Model.update()

// Delete
Model.destroy()

Last updated