Sequelize relation with WHERE IN (“ARRAY”)

做~自己de王妃 提交于 2020-07-08 18:24:33

问题


Is it possible to define a relationships in sequelize where multiple foreign keys are stored as an array in one field. Basically a belongsToMany but instead of an relation table all ids are stored comma separated in one field. Query would be with WHERE IN('1,5,7').


回答1:


You can do it, but definitely without foreign key constraints - there is no possibility of storing array of foreign keys. You can however create a column which will be an array of integers representing IDs of associated table. Then you just need to create some instanceMethods for retrieving and setting the array values (remember that the ARRAY type is only available in PostgreSQL).

I do not recommend this solution due to the fact that it does not ensure data consistency. Let's consider an example - user belongs to many categories with ids 1, 2 and 4. If you delete one of those categories, you need to remember to manually remove this id from categories array of user (with use of some hook or other tool), otherwise this user will still be assigned to a category that no longer exists.

const User = sequelize.define('User', {
    categories: DataTypes.ARRAY(DataTypes.INTEGER)
}, {
    instanceMethods: {
        getCategories: function(){
            return Category.findAll({
                where: {
                    id: { $in: this.get('categories') }
                }
            }).then(categories => {
                // if user's categories was [1, 2, 4]
                // it would return categories with id=1, id=2 and id=4
                return categories;
            });
        },
        setCategories: function(ids){
            return this.setDataValues('categories', ids).save().then(self => {
                return self;
            });
        }
    }
});



回答2:


To get sequelize query result with where condition for given array with using **Op.in** code to find result with in array as

var Sequelize = require('sequelize');
var Op = Sequelize.Op;
var arrayofTaskId = ['123', '456', '789'];
Tasks.findAll({
  where: {
    task_id: {
      [Op.in]: arrayofTaskId
    }
  }
}).then(function(result) {
  return res.json(result)
});


来源:https://stackoverflow.com/questions/42719750/sequelize-relation-with-where-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!