Reputation: 121
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?
Upvotes: 1
Views: 4496
Reputation: 51
The answer should be:
User.findAll({
where: sequelize.where(sequelize.fn('JSON_CONTAINS', sequelize.literal('colors'), '"blue"', '$'), 1)
});
Note:
Upvotes: 0
Reputation: 3157
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;
Upvotes: 1