Skip to content

Latest commit

 

History

History
798 lines (580 loc) · 13.6 KB

File metadata and controls

798 lines (580 loc) · 13.6 KB

Sequelize Queries Cheat Sheet

Sumário


Operadores

const { Op } = require("sequelize");
await Post.findAll({
  where: {
    [Op.and]: [{ a: 5 }, { b: 6 }],            // (a = 5) AND (b = 6)
    [Op.or]: [{ a: 5 }, { b: 6 }],             // (a = 5) OR (b = 6)
    someAttribute: {
      // Basics
      [Op.eq]: 3,                              // = 3
      [Op.ne]: 20,                             // != 20
      [Op.is]: null,                           // IS NULL
      [Op.not]: true,                          // IS NOT TRUE
      [Op.or]: [5, 6],                         // (someAttribute = 5) OR (someAttribute = 6)

      // Using dialect specific column identifiers (PG in the following example):
      [Op.col]: 'user.organization_id',        // = "user"."organization_id"

      // Number comparisons
      [Op.gt]: 6,                              // > 6
      [Op.gte]: 6,                             // >= 6
      [Op.lt]: 10,                             // < 10
      [Op.lte]: 10,                            // <= 10
      [Op.between]: [6, 10],                   // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15],               // NOT BETWEEN 11 AND 15

      // Other operators

      [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)

      [Op.in]: [1, 2],                         // IN [1, 2]
      [Op.notIn]: [1, 2],                      // NOT IN [1, 2]

      [Op.like]: '%hat',                       // LIKE '%hat'
      [Op.notLike]: '%hat',                    // NOT LIKE '%hat'
      [Op.startsWith]: 'hat',                  // LIKE 'hat%'
      [Op.endsWith]: 'hat',                    // LIKE '%hat'
      [Op.substring]: 'hat',                   // LIKE '%hat%'
      [Op.iLike]: '%hat',                      // ILIKE '%hat' (case insensitive) (PG only)
      [Op.notILike]: '%hat',                   // NOT ILIKE '%hat'  (PG only)
      [Op.regexp]: '^[h|a|t]',                 // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
      [Op.notRegexp]: '^[h|a|t]',              // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
      [Op.iRegexp]: '^[h|a|t]',                // ~* '^[h|a|t]' (PG only)
      [Op.notIRegexp]: '^[h|a|t]',             // !~* '^[h|a|t]' (PG only)

      [Op.any]: [2, 3],                        // ANY ARRAY[2, 3]::INTEGER (PG only)
    }
  }
});

Métodos

create

Template

await Model.create({
  <field1>: <value1>,
  ...,
  <fieldN>: <valueN>,
});

Exemplo

await User.create({
  fullName: "Jane Doe",
  email: "jane.doe@gmail.com",
});

Query MySQL Equivalente

INSERT INTO Users('fullName', 'email')
VALUES ('Jane Doe', 'jane.doe@gmail.com');

Documentação

Voltar para Sumário


update

Template

await Model.update(
  {
    <campo>: <valor>,
    ...,
    <campoN>: <valorN>
  },
  {
    where: { <expressão de filtragem> },
  },
);

Exemplo

await User.update(
  { lastName: "Doe" },
  {
    where: { lastName: null },
  },
);

Query MySQL Equivalente

UPDATE user
SET lastName = 'Doe'
WHERE lastName = 'null';

Documentação

Voltar para Sumário


destroy

Template

await Model.destroy({
  where: {
    <campo>: <valor>,
  },
});

Exemplo

await User.destroy({
  where: {
    firstName: "Jane",
  },
});

Query MySQL Equivalente

DELETE FROM User
WHERE firstname = 'Jane';

Documentação

Voltar para Sumário


findAll

SELECT simples

Template

await Model.findAll();

Exemplo

await User.findAll();

Query MySQL Equivalente

SELECT * FROM User;

Documentação

Voltar para Sumário


SELECT específico

Sem alias

Template

await Model.findAll({
  attributes: [ <atributo01>, <atributo02> ],
});

Exemplo

await Products.findAll({
  attributes: [ 'price', 'stock' ],
});

Query MySQL Equivalente

SELECT price, stock FROM Products;

Documentação

Voltar para Sumário


Com alias

Template

await Model.findAll({
  attributes: [ <atributo01>, [ <atributo02>, <alias> ], ..., <atributo03>]
});

Exemplo

await Products.findAll({
  attributes: ['price', ['product_name', 'name'], 'stock']
});

Query MySQL Equivalente

SELECT price, product_name AS name, stock FROM Products;

Documentação

Voltar para Sumário


SELECT Agregações

Template

await Model.findAll({
  attributes: [
    <attribute01>,
    [ sequelize.fn(<metodo>, sequelize.col(<coluna>)), <alias> ],
    ...,
    <attributeN>,
  ],
});

Exemplo

await Products.findAll({
  attributes: [
    'foo',
    [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'],
    'bar'
  ]
});

Query MySQL Equivalente

SELECT foo, COUNT(hats) AS n_hats, bar FROM Products;

Documentação

Voltar para Sumário


SELECT com WHERE

Template

await Model.findAll({
  where: {
    <campo1>: <valor>,
    ...,
    <campoN>: <valor>,
  },
});

Exemplo

await Post.findAll({
  where: {
    authorId: 2,
    status: 'active'
  }
});

Query MySQL Equivalente

SELECT * FROM post WHERE authorId = 2 AND status = 'active';

Documentação

Voltar para Sumário


GROUP BY

Template

await Model.findAll({ group: <campo> });

Exemplo

await Project.findAll({ group: 'name' });

Query MySQL Equivalente

GROUP BY name;

Documentação

Voltar para Sumário


LIMIT / OFFSET

Template

// limit
await Model.findAll({ limit: <numero> });
// offset
await Model.findAll({ offset: <numero> });
// limit & offset
await Model.findAll({ offset: <numero1>, limit: <numero2> });

Exemplo

// limit
await Project.findAll({ limit: 10 });
// offset
await Project.findAll({ offset: 8 });
// limit & offset
await Project.findAll({ offset: 5, limit: 5 });

Query MySQL Equivalente

-- limit
SELECT * FROM Project
LIMIT 10;
-- offset
SELECT * FROM Project
OFFSET 8;
-- limit & offset
SELECT * FROM Project
OFFSET 5
LIMIT 10;

Documentação

Voltar para Sumário


findByPK

Busca por um resultado, usando sua chave primária.

Template

const results = await Model.findByPk(valor);
if (project === null) {
  console.log('Not found!');
} else {
  console.log(results instanceof Model); // true
  //  a pk é <valor>
}

Exemplo

const project = await Project.findByPk(123);
if (project === null) {
  console.log('Not found!');
} else {
  console.log(project instanceof Project); // true
  //  a pk é 123
}

Documentação

Voltar para Sumário


findOne

Busca o primeiro resultado filtrado pela busca.

Template

const results = await Model.findOne({ where: { campo: valor } });
if (results === null) {
  console.log('Not found!');
} else {
  console.log(results instanceof Model); // true
  console.log(results.campo); // valor
}

Exemplo

const project = await Project.findOne({ where: { title: 'Título' } });
if (project === null) {
  console.log('Not found!');
} else {
  console.log(project instanceof Project); // true
  console.log(project.title); // 'Título'
}

Documentação

Voltar para Sumário


findOrCreate

Criará uma entrada na tabela, a menos que encontre um resultado que preencha as opções de consulta.

Obs.: Em ambos os casos, ele retornará uma instância (a instância encontrada ou a instância criada) e um booleano indicando se essa instância foi criada ou já existia.

Template

const [file, created] = await Model.findOrCreate({
  where: { filename: nome },
  defaults: {
    campo: valor
  }
});
console.log(file.filename);
console.log(file.campo);
console.log(created);
if (created) {
  console.log(file.campo);
}

Exemplo

const [user, created] = await User.findOrCreate({
  where: { username: 'Eric' },
  defaults: {
    job: 'Technical Lead JavaScript'
  }
});
console.log(user.username); // 'Eric'
console.log(user.job); // pode ou não ser 'Technical Lead JavaScript'
console.log(created); // Valor booleano que indica se a instancia foi criada ou nao
if (created) {
  console.log(user.job); // 'Technical Lead JavaScript'
}

Documentação

Voltar para Sumário


findAndCountAll

Método conveniente que combina findAll e count.

Template

const { count, rows } = await Model.findAndCountAll({
  where: {
    campo: {
      [Op.<operação>]: 'foo%'
    }
  }
});

Exemplo

const { Op } = require("sequelize");

const { count, rows } = await Project.findAndCountAll({
  where: {
    title: {
      [Op.like]: 'foo%'
    }
  },
  offset: 10,
  limit: 2
});

console.log(count);
console.log(rows);

Documentação

Sessão Operadores

Voltar para Sumário


count

Template

// simples
await Model.count();
// com filtro
const { Op } = require("sequelize");

await Model.count({
  where: {
    <campo>: {
      [Op.<operação>]: <valor>,
    },
  },
});

Exemplo

// com filtro
const { Op } = require("sequelize");

await Project.count({
  where: {
    id: {
      [Op.gt]: 25
    }
  }
});

Query MySQL Equivalente

SELECT COUNT('id') from project
WHERE 'id' > 25;

Documentação

Sessão Operadores

Voltar para Sumário


max

Template

await Model.max(<coluna>);

Exemplo

await User.max('age');
// com filtragem
const { Op } = require("sequelize");

await User.max('age', {
  where: {
     age: { [Op.lt]: 20 },
  },
});

Query MySQL Equivalente

SELECT MAX(age) FROM User;
--- com filtagem
SELECT MAX(age)
FROM User
WHERE age < 20;

Documentação

Sessão Operadores

Voltar para Sumário


min

Template

await Model.min(<coluna>);

Exemplo

await User.min('age');
// com filtragem
const { Op } = require("sequelize");

await User.min('age', {
  where: {
     age: { [Op.gt]: 5 },
  },
});

Query MySQL Equivalente

SELECT MIN(age) FROM User;
--- com filtagem
SELECT MIN(age)
FROM User
WHERE age > 5;

Documentação

Sessão Operadores

Voltar para Sumário


sum

Template

await Model.sum(<coluna>);

Exemplo

await User.sum('age');
// com filtragem
const { Op } = require("sequelize");

await User.sum('age', {
  where: {
     age: { [Op.gt]: 5 },
  },
});

Query MySQL Equivalente

SELECT SUM(age) FROM User;
--- com filtagem
SELECT SUM(age)
FROM User
WHERE age > 5;

Documentação

Sessão Operadores

Voltar para Sumário