嵌套的包含不提供结果

时间:2019-05-08 12:00:15

标签: sequelize.js

我有三个关联的模型,产品,目录成员,具有这些关联的目录

WebDriverWait wait = new WebDriverWait(driver, waitTime);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.XPath("")))

OR

WebDriverWait wait = new WebDriverWait(driver, waitTime);
wait.until(ExpectedConditions.elementToBeClickable(locator));

当我执行此嵌套查询时

Product.hasMany(CatalogMembership, { foreignKey: 'product_id' });
CatalogMembership.hasOne(Catalog, { targetKey: 'catalog_id', foreignKey: 'id' });

包括CatalogMemberships,但目录为空:

let products = await Product.findAll({
      where: {...},
      include: {
        model: CatalogMembership,
        where: { catalog_id: { [Op.in]: catalogIds } },
        include: {
          model: Catalog,
          attributes: ['name', 'id'],
        },
      },
    });

我确定其中有一些目录 console.log(products[0]) // --> /* { id: 1, catalog_memberships: [ { id: 23, catalog_id: 15, catalog: null, ... }, { id: 24, catalog_id: 16, catalog: null, ... } ], ... } */

我希望catalog属性不会为空,而是类似

CatalogMembership.catalog_id === Catalog.id

2 个答案:

答案 0 :(得分:0)

hasOne关系中没有 targetKey 。有 foreignKey (目标表中外键属性的名称)和 sourceKey (要用作源表中关联关系的属性的名称) ,默认情况下是源表的主键。

所以像这样使用

CatalogMembership.hasOne(Catalog, { foreignKey: 'catalog_id', sourceKey: 'id' });

答案 1 :(得分:0)

感谢您的答复。不幸的是,我的一般方法是错误的。我必须通过CatalogMembership与产品和目录建立n:m关联。因此,我向产品和目录添加了一个belongsToMany关联。

代码如下:

const Product = sequelize.define('product', {
  <some column names>
  ...
}, {
  timestamps: true,
  ...
});

const Catalog = sequelize.define('catalog', {
  <some column names>
  ...
}, {
  timestamps: true,
  ...
});


const CatalogMembership = sequelize.define('catalog_membership', {
  product_id: { type: Sequelize.INTEGER },
  catalog_id: { type: Sequelize.INTEGER },
  ...
}, {
  timestamps: true,
  ...
});

Product.belongsToMany(Catalog, { through: CatalogMembership, foreignKey: 'product_id', otherKey: 'catalog_id' });
Catalog.belongsToMany(Product, { through: CatalogMembership, foreignKey: 'catalog_id', otherKey: 'product_id' });

if (Meteor.isTest) {
  Product.sync();
  Catalog.sync();
  CatalogMembership.sync();
}

有了这些关联,就不需要嵌套查询:

let products = await Product.findAll({
      where: { ... },
      include: {
        model: Catalog,
        where: { id: { [Op.in]: catalogPostgresIds } },
        attributes: ['name', 'id'],
      },
      order: { ... },
    });