在Sequelize中使用parent模型作为条件

问题描述 投票:0回答:1

我找不到合适的文档,但我想要做的是根据顶级模型的ID限制包含。我不能说出来,但这是我希望实现的目标。

db.A.findAll({
  as: 'A',
  where: {
    ...
  },
  include: [{
    model: B,
    include: [{
      model: C,
      where: {
        color_id: A.color_id
      }
    }]
  }]
}

A与B关联,B有很多C.我试图限制获取C的数量,因为它导致查询非常慢。

编辑,添加模型关联:

const A = sequelize.define('A', {
  id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true,
    field: 'id'
  }, {
    tableName: 'a',
    underscored: true,
    indexes: [
      { fields: ['b'] }
    ]
  }
});

A.associate = function (models) {
  A.belongsTo(models.B);
  A.belongsTo(models.D);
}

const B = sequelize.define('B', {
  ...non-related-columns
});

B.associate = function (models) {
  B.hasMany(models.C);
  B.belongsTo(models.D);
  B.hasMany(models.E);
  B.hasMany(models.F);
}

const C = sequelize.define('C', {
  ...non-related-columns
});

C.associate = function (models) {
  C.belongsTo(models.B);
  C.belongsTo(models.D);
}
postgresql sequelize.js
1个回答
1
投票

更新:这是你在找什么?

B.findOne({
  where: {
    id: a.bId
  },
  include: [{ all: true, nested: true }]
})

我以前的回答:

我认为这应该有效。我把这个问题简化了一下。

const A = db.define('a', {
  name: Sequelize.STRING
})

const B = db.define('b', {
  name: Sequelize.STRING
})

const C = db.define('c', {
  type: Sequelize.STRING
})

A.belongsTo(B);
B.hasOne(A);

B.hasMany(C);
C.hasOne(B);

// given an A, find all Cs of type 'foo'

B.findOne({
  where: {
    id: a.bId
  }
})
.then(b => {
  return C.findAll({
    where: {
      bId: b.id,
      type: 'foo'
    }
  })
})
.the(foosWhichBelongToAThrougB => {
  //do something with your array of foos
})

我没有试图用一个查询来抓取它,而是将它分成两个查询。一个用于找到与A关联的B,然后用于找到与B关联的所有C并且在C模型中匹配某些内容。

© www.soinside.com 2019 - 2024. All rights reserved.