Sequelize에 대한공부- Model Querying - Basics(2)

공부중인 개발자·2021년 9월 1일
0

sequelize

목록 보기
6/6
post-thumbnail
초보개발자입니다. 틀린부분이 있다면 언제든지 말씀해주시면 감사합니다!

Creating in bulk

여러 레코드를 한번에 생성하는 bulkCreate 가 있다.

const captains = await Captain.bulkCreate([
  { name: 'Jack Sparrow' },
  { name: 'Davy Jones' }
]);
console.log(captains.length); // 2
console.log(captains[0] instanceof Captain); // true
console.log(captains[0].name); // 'Jack Sparrow'
console.log(captains[0].id); // 1 // (or another auto-generated value)

Captain 이라는 모델의 레코드를 2개 만드는 예시이다.

벌크생성을 할때 주의할점은 validations에 관한 부분이다.

const Foo = sequelize.define('foo', {
  bar: {
    type: DataTypes.TEXT,
    validate: {
      len: [4, 6]
    }
  }
});

// This will not throw an error, both instances will be created
await Foo.bulkCreate([
  { name: 'abc123' },
  { name: 'name too long' }
]);

// This will throw an error, nothing will be created
await Foo.bulkCreate([
  { name: 'abc123' },
  { name: 'name too long' }
], { validate: true });

예시에 나와있는 것처럼 모델을 만들 때 validate를 넣어놓고 bulkCreate를 하면 validate가 무시된다. 그러므로 bulkCreate를 할 때 validate가 있다면 예시에 나와있는것처럼 꼭 넣어야 작동한다.

사용자로부터 값을 직접 받을 때는 삽입하려는 열을 제한을 두는 것이 좋다고 한다. bulkCreate 에서도 field 는 먹힌다.

await User.bulkCreate([
  { username: 'foo' },
  { username: 'bar', admin: true }
], { fields: ['username'] });
// Neither foo nor bar are admins.

Ordering and Grouping

query문 ORDER BY 와 GROUP BY 를 하는 법에 대해서 공부하겠다.

Subtask.findAll({
  order: [
    // Will escape title and validate DESC against a list of valid direction parameters
    ['title', 'DESC'],

    // Will order by max(age)
    sequelize.fn('max', sequelize.col('age')),

    // Will order by max(age) DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],

    // Will order by  otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],

    // Will order an associated model's createdAt using the model name as the association's name.
    [Task, 'createdAt', 'DESC'],

    // Will order through an associated model's createdAt using the model names as the associations' names.
    [Task, Project, 'createdAt', 'DESC'],

    // Will order by an associated model's createdAt using the name of the association.
    ['Task', 'createdAt', 'DESC'],

    // Will order by a nested associated model's createdAt using the names of the associations.
    ['Task', 'Project', 'createdAt', 'DESC'],

    // Will order by an associated model's createdAt using an association object. (preferred method)
    [Subtask.associations.Task, 'createdAt', 'DESC'],

    // Will order by a nested associated model's createdAt using association objects. (preferred method)
    [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],

    // Will order by an associated model's createdAt using a simple association object.
    [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],

    // Will order by a nested associated model's createdAt simple association objects.
    [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
  ],

  // Will order by max age descending
  order: sequelize.literal('max(age) DESC'),

  // Will order by max age ascending assuming ascending is the default order when direction is omitted
  order: sequelize.fn('max', sequelize.col('age')),

  // Will order by age ascending assuming ascending is the default order when direction is omitted
  order: sequelize.col('age'),

  // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
  order: sequelize.random()
});

Foo.findOne({
  order: [
    // will return `name`
    ['name'],
    // will return `username` DESC
    ['username', 'DESC'],
    // will return max(`age`)
    sequelize.fn('max', sequelize.col('age')),
    // will return max(`age`) DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],
    // will return otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
    // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
    [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
  ]
});

엄청난 양의 예시가 있는데 order: [[Model, column, option]]으로 보인다. Model은 없어도 되고 2개가 있어도 되는것같다. 여기서 알아야할 문법은 sequelize.col() / sequelize.fn("QUERY", columns) 이 둘인데 .col은 해당 컬럼의 이름을 이용하는 것이고 .fn은 실제쿼리문을 이용할 수 있게 해주는 것이다.
Group은 Order 와 똑같은 문법을 사용한다고 한다.

Limits and Pagination

The limit and offset options allow you to work with limiting / pagination:

// Fetch 10 instances/rows
Project.findAll({ limit: 10 });

// Skip 8 instances/rows
Project.findAll({ offset: 8 });

// Skip 5 instances and fetch the 5 after that
Project.findAll({ offset: 5, limit: 5 });

Usually these are used alongside the order option.

페이지에 일정양의 게시물을 보여줄때 사용하는 방법이다.
limit은 레코드를 보내주는 양의 한계를 뜻하고 offset은 offset 만큼을 제하고 다음부터 레코드를 건내주는 것이다.

count

테이블의 항목 갯수를 세는 용도이다.

const amount = await Project.count({
  where: {
    id: {
      [Op.gt]: 25
    }
  }
});
console.log(`There are ${amount} projects with an id greater than 25`);

위의 예시는 25이상의 id 만 숫자를 세는 것이다.

마지막으로 max,min, sum 이다.

// 데이터 예시는 5, 10 40 이고 각각 최대값 최소값 합에 대해 말해주고 있다.
await User.max('age'); // 40
await User.max('age', { where: { age: { [Op.lt]: 20 } } }); // 10
await User.min('age'); // 5
await User.min('age', { where: { age: { [Op.gt]: 5 } } }); // 10
await User.sum('age'); // 55
await User.sum('age', { where: { age: { [Op.gt]: 5 } } }); // 50

Querying 부분은 기본적으로 많이 작성을 해보고 어떻게 데이터를 뽑아내야할지 고민해봐야겠다.

profile
열심히 공부하자

0개의 댓글