9033 / coding_programming

coding programming of problems
MIT License
0 stars 0 forks source link

sequelize (javascript) #12

Open 9033 opened 2 years ago

9033 commented 2 years ago

시퀄라이즈 관련

9033 commented 2 years ago

hooks

언제 hook이 실행되는지 알 수 있게 console로 보여주는 hook을 지정하는 함수.

(function(model){
  model.beforeBulkCreate(async (instances, options) => {
    console.log('beforeBulkCreate');
  });
  model.beforeBulkDestroy(async (options) => {
    console.log('beforeBulkDestroy');
  });
  model.beforeBulkUpdate(async (options) => {
    console.log('beforeBulkUpdate');
  });
  model.beforeValidate(async (instance, options) => {
    console.log('beforeValidate');
  });
  model.afterValidate(async (instance, options) => {
    console.log('afterValidate');
  });
  model.validationFailed(async (instance, options, error) => {
    console.log('validationFailed');
  });
  model.beforeCreate(async (instance, options) => {
    console.log('beforeCreate');
  });
  model.beforeDestroy(async (instance, options) => {
    console.log('beforeDestroy');
  });
  model.beforeUpdate(async (instance, options) => {
    console.log('beforeUpdate');
  });
  model.beforeSave(async (instance, options) => {
    console.log('beforeSave');
  });
  model.beforeUpsert(async (values, options) => {
    console.log('beforeUpsert');
  });
  model.afterCreate(async (instance, options) => {
    console.log('afterCreate');
  });
  model.afterDestroy(async (instance, options) => {
    console.log('afterDestroy');
  });
  model.afterUpdate(async (instance, options) => {
    console.log('afterUpdate');
  });
  model.afterSave(async (instance, options) => {
    console.log('afterSave');
  });
  model.afterUpsert(async (created, options) => {
    console.log('afterUpsert');
  });
  model.afterBulkCreate(async (instances, options) => {
    console.log('afterBulkCreate');
  });
  model.afterBulkDestroy(async (options) => {
    console.log('afterBulkDestroy');
  });
  model.afterBulkUpdate(async (options) => {
    console.log('afterBulkUpdate');
  });
})(User);
9033 commented 2 years ago
hooks create bulkCreate findOrCreate update destroy build save find save
beforeValidate 1   1 1   1 1
afterValidate 2   2 2   2 2
validationFailed              
beforeBulkCreate   1          
beforeBulkDestroy         1    
beforeBulkUpdate       3      
beforeCreate 3   3     3  
beforeDestroy              
beforeUpdate             3
beforeSave 4   4     4 4
beforeUpsert              
afterCreate 5   5     5  
afterDestroy              
afterUpdate             5
afterSave 6   6     6 6
afterUpsert              
afterBulkCreate   2          
afterBulkDestroy         2    
afterBulkUpdate       4      
9033 commented 2 years ago

여러 컬럼에 합계를 출력할때

await model.findAll({
  attributes: [
    [Sequelize.fn('SUM', Sequelize.col('amount'), 'amount'],
    [Sequelize.fn('SUM', Sequelize.col('count'), 'count'],
    [Sequelize.fn('SUM', Sequelize.col('volume'), 'volume'],
  ],
})

바로 생각나는건 위와 같은 코드다. 줄을 복사해서 해당 컬럼명만 바꾸면 되니까.

const attributes = [
  'amount',
  'count',
  'volume',
]
await model.findAll({
  attributes: [
    ...attributes.map(col=>[Sequelize.fn('SUM', Sequelize.col(col)), col]),
  ],
})
await model.findAll({
  attributes: [
    ...[
      'amount',
      'count',
      'volume',
    ].map(col=>[Sequelize.fn('SUM', Sequelize.col(col)), col]),
  ],
})

이런식으로 전개 연산자와 map함수를 써주면 더 간편하다.

9033 commented 2 years ago

컬럼으로 그룹핑한 목록

목록을 출력할때 총 몇 페이지가 있는지 보여주기 위해 전체 열의 수도 필요할 때가 많다.

const { rows, count } = await model.findAndCountAll({
  group: ['user_id'],
})

위와 같이 하면 count안에 각 user_id컬럼별로 갯수를 넣어서 출력을 한다. 혹은 include된 모델의 열의 수 까지 카운트 되는 경우가 있다. 이와같이 의도와는 다르게 동작할 떄가 있다.

const rows = await model.findAll({
  group: ['user_id'],
})
const count = await model.count({
  distinct: true,
  col: 'user_id',
})

이런식으로 하면 각 user_id로 그룹핑된 목록의 결과의 열의 수를 출력해 준다. 이때 user_id컬럼에 값이 중복되는 경우는 없기 때문에 distinct: true옵션을 넣어준다