【问题标题】:How can I use a relation in the where of a sequelize query?如何在 sequelize 查询的 where 中使用关系?
【发布时间】:2020-01-01 05:29:06
【问题描述】:

我有两张桌子,我们称它们为“人”和“汽车”,关系如下。一个人可以有 1 辆或 0 辆汽车。在后一种情况下,Car 表中将没有条目。

Person:
  firstName,
  lastName,
  ....
  hasOne(Car, {
    foreignKey: 'personId',
    as: 'personsCar'
  })
Car:
  personId,
  colour,
  ...
  belongsTo(Person, {
    foreignKey: 'personId',
    as: 'carOwner'
  })

使用 Sequelize 我想从 Person 表中获取所有 “绿色”汽车或没有汽车的人

仅尝试使用以下任何颜色的汽车获取人员会给出错误“Person.personsCar 列不存在”,我如何才能正确引用查询位置中的关系?

Person.findAll({
  include: [
    model: Car,
    as: 'personsCar',
    attributes: ['colour'],
  ],
  where: {
    personsCar: {
      [op.eq]: null,
    },
  },
})

【问题讨论】:

    标签: node.js postgresql graphql sequelize.js


    【解决方案1】:

    你可以这样做:

    Person.findAll({
        include: [
            model: Car,
            as: 'personsCar',
            attributes: ['colour'],
            where: {
                colour : 'green' // <---- YOUR COLOUR
            },
        ],
    })
    

    【讨论】:

    • 感谢维韦克!这是我所要求的确切答案,但我错过了一个重要的标准,我想得到没有车的人。
    猜你喜欢
    • 2016-12-19
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-15
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多