> For the complete documentation index, see [llms.txt](https://adam-37.gitbook.io/joomadeung/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://adam-37.gitbook.io/joomadeung/node.js/node.js-express-mysql/sequelize-query-js.md).

# Sequelize query문(JS)

SQL문

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

Sequelize문

```jsx
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);
  });
```

```jsx
Select * FROM nodejs.users;

User.findAll({})
```

```jsx
SELECT name, married FROM nodejs.users;

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

***

### 관계 쿼리

```jsx
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을 쓸 수 있음

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

### Sequelize에서 CRUD

```jsx
// Create
Model.create()

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

// Update
Model.update()

// Delete
Model.destroy()
```
