简体   繁体   中英

How to call a Sequelize MySQL JSON query?

I have a User model that includes a json data type. I'm using MySQL as my database, but when looking through their documentation for how to query using JSON, there appears to be nothing on MySQL.

const User = db.define("User", {
  UserId: {
    primaryKey: true,
    type: Sequelize.INTEGER
  },
  colors: {
    type: Sequelize.JSON,
    allowNull: false
  }
}

I have Users that have an id, and an array with their favorite colors in it.

UserId    | colors
    1     |["black, "blue"]
    2     |["blue"]
    3     |["black"]   

I want to query for all users that have the favorite color blue. I tried querying like this,

User.findAll({ where: {colors: ["blue"]} })

and expected to be returned users 1 and 2, but this doesn't work and I have not found any sources online that shows what to do. Some stackoverflows have solutions for JSON objects, like this Sequelize, MySQL - Filtering rows in table with JSON column values , but I can't find any sources for arrays. Any solutions?

You can use sequelize.fn and sequelize.col methods to specify an SQL function call and a table column, respectively. This way you can create your own where condition.

User.findAll({
  where: sequelize.where(sequelize.fn('JSON_CONTAINS', sequelize.col('colors'), sequelize.literal('blue'), sequelize.literal('$')), 1)
});

It corresponds to below mysql query:

// SELECT * FROM Users WHERE JSON_CONTAINS(colors, 'blue', '$') = 1;

The answer should be:

User.findAll({
      where: sequelize.where(sequelize.fn('JSON_CONTAINS', sequelize.literal('colors'), '"blue"', '$'), 1)
});

Note:

  • The 2nd parameter of JSON_CONTAINS should be string.
  • Because the data of question is an array of string, so we need to add a " for searching keyword (eg: "blue").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM