📜  sequelize findall in array (1)

📅  最后修改于: 2023-12-03 15:34:56.396000             🧑  作者: Mango

Sequelize findAll in Array

Sequelize is a promise-based ORM for Node.js that works with various SQL databases, such as MySQL, PostgreSQL, SQLite, and MSSQL. The findAll method is used to query the database for all matching records in a table. In this guide, we will discuss how to use the findAll method to search for records in an array.

Search for Records in an Array

To search for records in an array using Sequelize's findAll method, we need to perform the following steps:

  1. Create a Sequelize model for the table we want to search.
  2. Define the array of values we want to search for.
  3. Call the findAll method with the where clause and the in operator.

Here is an example code snippet that demonstrates how to search for records in an array:

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

const User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    allowNull: false
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false
  }
});

// Create some test data
(async () => {
  await sequelize.sync({ force: true });
  await User.bulkCreate([
    { username: 'john_doe', email: 'john_doe@test.com' },
    { username: 'jane_doe', email: 'jane_doe@test.com' },
    { username: 'bob_smith', email: 'bob_smith@test.com' },
    { username: 'alice_smith', email: 'alice_smith@test.com' }
  ]);
})();

// Define the array of values to search for
const usernames = ['john_doe', 'bob_smith'];

// Search for records in the User table where the username is in the array
User.findAll({
  where: {
    username: {
      [Sequelize.Op.in]: usernames
    }
  }
}).then(users => {
  console.log(users);
});

In this example, we create a User model with a username and email fields. We also create some test data using the bulkCreate method. Then, we define an array of usernames to search for.

Next, we call the findAll method on the User model and pass in an object with a where clause that checks if the username is in the usernames array using the in operator.

Finally, we log the returned array of matching users to the console.

Conclusion

In conclusion, the findAll method in Sequelize allows us to search for records in an array by using the where clause and the in operator. By following the steps outlined in this guide, you can easily search for records in an array with Sequelize.