📅  最后修改于: 2023-12-03 15:20:06.017000             🧑  作者: Mango
Sequelize is a powerful object-relational mapping (ORM) library for Node.js that allows developers to interact with SQL databases using JavaScript. The QueryInterface is a module of Sequelize that provides a simple and consistent way of executing SQL queries.
In this article, we will be focusing on how to use the QueryInterface to perform SELECT queries in Sequelize.
Before we dive into the code, make sure you have Sequelize installed in your project. You can install it by running the following command in your terminal:
npm install sequelize
The syntax for performing SELECT queries using the QueryInterface is as follows:
queryInterface.select(
tableName: string,
attributes?: Array<string>,
options?: Object
): Promise<Array<any>>
The select
method takes the following arguments:
tableName
: The name of the table that you want to perform the SELECT query on.attributes
(optional): An array of strings that represent the columns that you want to retrieve. If this argument is not provided, all columns will be retrieved.options
(optional): Additional options to specify the behavior of the query.The select
method returns a Promise that resolves with an array of rows from the table that match the specified criteria.
Let's look at an example of how to perform a simple SELECT query using the QueryInterface.
const { Sequelize, QueryTypes } = require('sequelize');
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'database.sqlite'
});
sequelize.queryInterface.select('users', ['id', 'name'], {
where: {
age: {
[sequelize.Op.gt]: 18
}
}
}).then(results => {
console.log(results);
}).catch(error => {
console.error(error);
});
In this example, we are selecting the id
and name
columns from the users
table where the age
column is greater than 18. The results are then logged to the console.
In this article, we have learnt how to use the QueryInterface to perform SELECT queries in Sequelize. With the QueryInterface, we can execute SQL queries in a simple and consistent manner, making it easier for developers to work with SQL databases in Node.js.