如何使用 Sequelize 使用不同的别名和条件连接同一个表 2 次?

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

我有3张桌子:

用户表:

---------------
userId | name 
---------------
1      | Alice
2      | Bob
3      | Charly
---------------

项目表:

-------------------------------------
projectId | userId | state  | color
-------------------------------------
4         | 1      | active | red
5         | 1      | closed | blue
6         | 2      | closed | green
7         | 3      | active | yellow
-------------------------------------

主题表:

--------------------------------
topicId | projectId | topicName
--------------------------------
7       | 4         | D
8       | 4         | e
9       | 5         | D
10      | 6         | D
--------------------------------

协会:

User.hasMany(model.Project)
Project.hasMany(model.Topics)

我想找到所有

User
的人:

  • 至少有一个
    project
    ,根据条件与某些
    topic
    连接(其中
    name='D'
    );
  • 包括所有处于
    projects
    状态的
    active

所以,结果,我想要

--------------------------------------
userId | userName | projectId | color
--------------------------------------
1      | Alice    | 4         | red
2      | Bob      | 6         | green
--------------------------------------

类似这样的:

const users = await User.findAll({
    include: [{
        model: Project,
        include: [{
            model: Topics,
            where: { name: 'D' },
            attributes: [],
        }],
        attributes: [],
    }, {
        model: Project,
        where: { status: 'active'},
        required: false,
        attributes: ['color'],
    }]
})

如果我再添加一个关联就可以解决这个问题:

User.hasMany(models.Project, { as: 'ProjectTopics' });

并添加到第 4 行的查询

as: ProjectTopics
。 但我不想使用相同的键与同一个表建立两个关联,只是使用不同的别名。

文档中有一行:

options.include[].through.as  
The alias for the join model, in case you want to give it a different name than the default one.

您能帮助我了解它的工作原理以及如何使用它来解决我的问题吗?

javascript node.js postgresql sequelize.js
1个回答
-1
投票

在用户模型中

User.hasMany(model.Project,{foreignKey: `userId `, as: `user`})
model.Project.hasMany(User,{foreignKey: "userId "})

在项目模型中

Project.hasMany(model.Topics,{foreignKey:  "projectId", as: `project`})
model.Topics.hasMany(Project,{foreignKey: "projectId"})

第三个关联与用户和项目表无关

假设用户表活动列可以轻松创建与用户和项目表的关系

// incase active column available only 
User.hasMany(model.Project,{foreignKey: `active`, as: `activeUser`})
model.Project.hasMany(User,{foreignKey: `active`})

下一步

users = await User.findAll({
    include: [{
        model: Project,
        include: [{
            model: Topics,
            where: { name: 'D' },
            attributes: [],
      association:`user`
        }],
        attributes: [],
    }, {
        model: Project,
        where: { status: 'active'},
        required: false,
        attributes: ['color'],
        association: 'project'

    },{
        model: Project,
        where: { status: `active`},
        required: false,
        attributes: ['color'],
        association: `activeUser`

    }]
})
© www.soinside.com 2019 - 2024. All rights reserved.