简体   繁体   English

如何调用 Sequelize MySQL JSON 查询?

[英]How to call a Sequelize MySQL JSON query?

I have a User model that includes a json data type.我有一个包含 json 数据类型的用户 model。 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.我正在使用 MySQL 作为我的数据库,但是在查看他们的文档以了解如何使用 JSON 进行查询时,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.我的用户有一个 ID,还有一个数组,其中包含他们最喜欢的 colors。

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.并期望返回用户 1 和 2,但这不起作用,我还没有在网上找到任何资源来说明该怎么做。 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?一些计算器有针对 JSON 对象的解决方案,例如Sequelize,MySQL - Filtering rows in table with JSON column values ,但我找不到 arrays 的任何来源。任何解决方案?

You can use sequelize.fn and sequelize.col methods to specify an SQL function call and a table column, respectively.您可以使用sequelize.fnsequelize.col方法分别指定 SQL function 调用和表列。 This way you can create your own where condition.这样您就可以创建自己的 where 条件。

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

It corresponds to below mysql query:对应下面的 mysql 查询:

// 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. JSON_CONTAINS 的第二个参数应该是字符串。
  • Because the data of question is an array of string, so we need to add a " for searching keyword (eg: "blue").因为问题的数据是一个字符串数组,所以我们需要添加一个“用于搜索关键字(例如:“blue”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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