繁体   English   中英

如何通过查询字典数组中的键/值来查找Sequelize中的实例

[英]How to find instances in Sequelize by querying a key/value in an array of dictionaries

我正在将一个Web应用程序数据库从Mongoose迁移到Sequelize (以便我可以使用MySQL)。 我正在寻找这个Mongoose查询的Sequelize等价物:

models.Instance.find({ "events.id": eventID })

该查询使我能够找到包含id == eventID的事件(在events数组中)的实例。

我尝试了以下但是没有给出所需的结果:

models.Instance.findAll({
    raw: true,
    where: {
      "events.id": eventID
    }
  })

Sequelize中的Instance模型如下所示:

module.exports = function(sequelize, DataTypes) {
  var Instance = sequelize.define('Instance', {
    name: {
      type: DataTypes.STRING,
    },
    description: {
      type: DataTypes.STRING,
    },
    events: {
      type: DataTypes.JSON,
    }
  });

  return Instance;
};

我找到了一个解决方案,涉及切换到PostgreSQL数据库,因为它支持JSONB数据类型

在我的实例模型中更改数据类型后 -

    events: {
      type: DataTypes.JSONB,
    }

我将此代码用于我的查询:

var models  = require('../../models');
const Op = models.Sequelize.Op;

models.Instance.findAll({
  raw: true,
  where: {
    events_current: {[Op.contains]:[{
        id: eventID
      }]
    }
  }
})

暂无
暂无

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

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