本文介绍了对连接表进行 Sequelize 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 sequelize 查询连接表:这是模型:

I am trying to querying a join table using sequelize:Here is the model:

db.client.belongsToMany(db.user, {
  through: db.clientUser,
   onDelete: 'cascade',
});
db.user.belongsToMany(db.client, {
   through: db.clientUser,
 });

这就是我想要做的:

db.user.findAll({
      where: {
        group_id: 1,
      },
      include: [{
        model: db.clientUser,
        where: {
          is_manager: 1,
        }
      }],
      raw: true,
    })

但是我得到以下错误:client_user is not associated to user!

知道导致此问题的原因是什么吗?

Any idea what could be the cause of this issue?

推荐答案

你声明了 clientuser 之间的关系客户端用户.虽然迂腐,但它的抱怨在技术上是正确的:在 clientclientUser 之间没有明确声明的关系.也不应该有:你的 belongsToMany 关系应该照顾到这一点.可以调整您的查询以处理这种关系.

You declared a relationship between client from user through clientUser. Although pedantic, its complaint is technically correct: there is no explicitly declared relationship declared between client and clientUser. Nor should there be: your belongsToMany relationship should take care of that. Your query can be adjusted to work with this relationship.

注意:我不知道 group_id 和 is_manager 是在哪些表中找到的.可能需要对其进行洗牌.

db.user.findAll({
  where: {
    group_id: 1,
  },
  include: [{
    model: db.client,
    through: {
      where: {
        is_manager: 1, // Assuming clientUser.is_manager?
      },
    }],
  raw: true,
})

这篇关于对连接表进行 Sequelize 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 08:40