sequelize.query code example

Example 1: sequelize query result

sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread(function(results,
  	metadata) {
  // Results will be an empty array and metadata will contain the number of 
  // affected rows.
})

/* In cases where you don't need to access the metadata you can pass in a query 
type to tell sequelize how to format the results. For example, for a simple 
select query you could do: */

sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
  .then(function(users) {
    // We don't need spread here, since only the results will be returned for 
    // select queries
  })

Example 2: sequelize get where

// Example
const Tokens = db.define('tokens', {
    guid: {
        type: sequelize.STRING
    }
});
// The basics of Sequelize Get Where
Tokens.findAll({
        where: { guid: 'guid12345' }
    }).then(tokens => {
        console.log(tokens);
    }).catch(err => console.log('error: ' + err));;
// is equal to >> SELECT * FROM Tokens WHERE guid = 'guid12345'

Example 3: sequelize like search

const Sequelize = require('sequelize');
const Op = Sequelize.Op;

let data: Array<any> = await MyDataSequelizeAccess.findAll({
  where: {
    name: {
      [Op.like]: '%Bob%'
    }
  }
});

Example 4: sequelize

$ npm install --save sequelize # This will install v5
$ npm install --save-dev sequelize-cli
 
# And one of the following: 
$ npm install --save pg pg-hstore # Postgres 
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server 

//Generate Models Auto with sequelize-auto
$ npm install mysql2 -g
$ npm install -g sequelize-auto-v2

//Comand to generate models from database
sequelize-auto -o "./models" -d schema -h localhost -u user -p 3306 -x password -e dialect

Exemple:
sequelize-auto -o "./models" -d nomeDoShema -h localhost -u usuarioDaConexao -p 3306 -x senhaDaConexao -e mysql

Example 5: sequelize documentation

const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

class User extends Model {}
User.init({
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });

sequelize.sync()
  .then(() => User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  }))
  .then(jane => {
    console.log(jane.toJSON());
  });

Example 6: sequelize .all()

yourTableModel.findAll({
  //optional filters
  where: {},
  raw: true,
})