【问题标题】:Sequelize find based on association and nested [Op.and]Sequelize find 基于关联和嵌套 [Op.and]
【发布时间】:2022-08-18 02:34:04
【问题描述】:

我写在这里是因为我完全迷路了。我想做一个基于关联和嵌套[Op.and]的findall,但我做不到。让我解释。

我有两个表(汽车和属性),这两个表之间有关联(一辆车,可以有多个属性)。数据如下所示:

{
  \"car\": \"BMW M5\",
  \"properties\": [
    {
      \"name\": \"make\",
      \"value\": \"bmw\"
    },
    {
      \"name\": \"color\",
      \"value\": \"blue\"
    }
  ]
},
{
  \"car\": \"AUDI A3\",
  \"properties\": [
    {
      \"name\": \"make\",
      \"value\": \"audi\"
    },
    {
      \"name\": \"color\",
      \"value\": \"black\"
    }
  ]
},

我正在尝试做的是“找到所有”宝马制造的所有蓝色汽车。从逻辑上讲,我会看到这样的事情:

( properties.name = make & properties.value = audi ) & ( properties.name = color & properties.value = blue )

因此,根据这个逻辑,我尝试在下面创建 sequelize 命令,但没有成功:

const cars = await models.Car.findAll({
  include: [{
    model: models.Properties,
    required: false,
  }],
  where: {
    [Sequelize.Op.and]:[
      {[Sequelize.Op.and]: [{\"$properties.name$\": \"make\"}, {\"$properties.value$\": \"bmw\"}]},
      {[Sequelize.Op.and]: [{\"$properties.name$\": \"color\"}, {\"$properties.value$\": \"blue\"}]},
    ]
});

显然,当我这样做时,它只需要最后一个 [Op.and] ([Sequelize.Op.and]: [{\"$properties.name$\": \"color\"}, {\"$properties.value$\": \"blue\"}]),其他的似乎没有被考虑在内。

也许我错了,但我尝试了几种可能性,但我不知道该怎么做。任何帮助将不胜感激,在此先感谢大家。

    标签: javascript orm sequelize.js


    【解决方案1】:

    看来您使where 条件过于复杂:

    const cars = await models.Car.findAll({
      include: [{
        model: models.Properties,
        required: false,
      }],
      where: {
        [Sequelize.Op.and]:[
          {
           "$properties.name$": "make",
           "$properties.value$": "bmw"
          },
          {
           "$properties.name$": "color", 
           "$properties.value$": "blue"
          },
        ]
       }
    });
    

    如果您在同一组条件中有different 道具,那么您可以使用一个对象将它们与AND 运算符结合起来。

    【讨论】:

      猜你喜欢
      • 2021-09-08
      • 2017-08-15
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 2013-09-21
      • 2016-08-22
      • 1970-01-01
      相关资源
      最近更新 更多