📜  sequelize contains (1)

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

Sequelize Contains

Sequelize is a popular Node.js ORM (Object Relational Mapping) library that provides a simple and powerful way to interact with various SQL databases such as MySQL, SQLite, and PostgreSQL. One of the most commonly used features of Sequelize is the "contains" method, which allows the user to search for records that contain a specific value in a certain column.

Basic Usage

To use the "contains" method with Sequelize, you first need to create a Sequelize model that corresponds to the table you want to search in. Here's an example of how to create a simple model for a "users" table:

const { Sequelize, Model, DataTypes } = require('sequelize');

const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql'
});

class User extends Model {}

User.init({
  username: DataTypes.STRING,
  email: DataTypes.STRING,
  password: DataTypes.STRING
}, { sequelize, modelName: 'user' });

Once you have a model defined, you can use the "contains" method to search for records that contain a specific value in a certain column. Here's an example of how to search for all users whose usernames contain the string "john":

const Op = Sequelize.Op;

const users = await User.findAll({
  where: {
    username: {
      [Op.contains]: 'john'
    }
  }
});

console.log(users);

This will output an array of all users whose usernames contain the string "john".

Case-Insensitive Search

By default, the "contains" method searches for records that contain a specific value in a case-sensitive manner. However, you can perform a case-insensitive search by using the "iLike" operator instead of "contains". Here's an example of how to perform a case-insensitive search for all users whose usernames contain the string "john":

const users = await User.findAll({
  where: {
    username: {
      [Op.iLike]: '%john%'
    }
  }
});

console.log(users);

This will output an array of all users whose usernames contain the string "john" in a case-insensitive manner.

Conclusion

In conclusion, the "contains" method is a powerful feature of Sequelize that allows you to easily search for records that contain a specific value in a certain column. By combining the "contains" method with other Sequelize features such as the "where" clause and the "Op" object, you can perform complex searches in a simple and efficient manner.