如何查询自定义连接 table

How to query custom defined join table

我有三个型号usertabsubscription。用户可以订阅多个选项卡,而选项卡可以有多个订阅者。 user --* subscription *-- tab

来自navicat的图表

sequelize.define('subscription', {})

Tab.belongsToMany(User, { through: Subscription })
User.belongsToMany(Tab, { through: Subscription })

如何获取特定选项卡的所有订阅者或特定用户订阅的所有选项卡? 我可以在两个查询中做到这一点,但它必须在一个查询中实现。

我已经尝试了 whereincludethrough 的所有可能组合,我不想在这里分享。每次我尝试从任何一方访问订阅时,我都会得到 subscription (subscriptions) is not associated to user.

我正在努力让这样的东西发挥作用。

  await Tab.findAll({
    where: { name: ctx.params.tabname },
    include: [{
      model: Subscription,
      through: {
        where: { userUsername: ctx.params.username }
      }
    }]
  })

belongsToMany 的问题是直接创建 link 到目标实体。因此,要让所有用户访问特定选项卡,您必须这样做

Tab.findAll({
 include: [{
    model: User
  }]
});

当您真的不想从订阅实体获取任何数据时,这很有效。

如果您想 select 来自订阅实体的任何数据,您需要稍微修改您的关系。

Tab.hasMany(Subscription);
Subscription.belongsTo(Tab);

User.hasMany(Subscription);
Subscription.belongsTo(User);

这将创建从选项卡到订阅的一对多关系,并添加从订阅到选项卡的反向绑定。用户也一样。

然后您可以查询特定标签的所有订阅(含用户信息)或特定用户的所有订阅(含标签信息),如下所示:

Tab.findAll({
  include: [{
    model: Subscription,
    include: [{
      model: User
    }]
  }]
});

User.findAll({
  include: [{
    model: Subscription,
    include: [{
      model: Tab
    }]
  }]
});

希望对您有所帮助!