📜  sequelize findall return - Javascript (1)

📅  最后修改于: 2023-12-03 14:47:24.362000             🧑  作者: Mango

Sequelize FindAll Return
Introduction

Sequelize is an Object-Relational Mapping (ORM) tool that is used to interact with relational databases (e.g. MySQL, PostgreSQL, SQLite). One of the most important methods used in Sequelize is findAll(). This method allows you to retrieve all data from a table based on certain conditions.

Syntax

The syntax for findAll() method in Sequelize is as follows:

ModelName.findAll({
  attribute: value,
  where: {
    // conditions
  },
  order: [
    // column name and direction
  ],
  limit: value,
  offset: value,
  raw: true/false
})
Parameters
  • attribute: A string or an array of strings representing the attributes to select from the table.
  • where: An object containing the conditions for selecting data from the table. You can use operators like Op.and, Op.or, Op.gt, Op.lt, etc. to define the conditions.
  • order: An array of arrays containing the column name and order to sort the results. The order can be either ASC or DESC.
  • limit: A number representing the maximum number of rows to return.
  • offset: A number representing the number of rows to skip before returning.
  • raw: A boolean indicating whether to return the raw SQL data or not.
Example

Let's look at an example of using findAll() method in Sequelize to retrieve all data from a table:

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

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true
  },
  age: {
    type: DataTypes.INTEGER
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE
  }
});

async function getAllUsers() {
  const users = await User.findAll();
  console.log(users);
}

getAllUsers();

In this example, we define a User model with the required attributes. We then create a function getAllUsers() which uses the findAll() method to retrieve all data from the User table. The returned data from findAll() method is stored in the users variable which is then logged to the console.

Conclusion

In conclusion, findAll() is a powerful method in Sequelize that allows you to retrieve all data from a table based on certain conditions. It provides a wide range of options to customize your queries to fit your specific needs.