Is there a way to query a table with a where clause on a related table but still grab all related content to the original table with Sequelize?

女生的网名这么多〃 提交于 2019-12-11 06:54:52

问题


I have two tables that are related. Table A and Table B. Table A has a one-to-many relationship with Table B. I want to retrieve all instances of A that has an instance of B related to it with a status of pending.

The query used is shown below, what I'm trying to achieve is to grab all instances of A with an instance of B whose status is pending.

await A.findAll({
    limit,
    offset,
    include: [
      {
        model: B,
        where: {
          status: 'pending'
        }
      }
    ]
  });

The code above returns multiple instances of the same instance of A which isn't the expected result. If an instance of A has two instances of B related to it with a status of pending, it'll return A twice with just the instance that's pending.

A sample of table B is shown below

Table B
id     name     status       a_id
1      sample1  completed    1
2      sample2  pending      1
3      sample3  pending      1
4      sample4  pending      2
5      sample5  completed    3
5      sample6  completed    3
5      sample7  completed    3

An example of table A is shown below

Table A
id      name
1       typeA
2       typeB
3       typeC

If I run the query for with this data, I get an output like this:

[
    {
        id: 1,
        name: 'typeA',
        Bs: [
            { id: 2, name: 'sample2', status: 'pending' }
        ]
    },
    {
        id: 1,
        name: 'typeA',
        Bs: [
            { id: 3, name: 'sample3', status: 'pending' }
        ]
    },
    {
        id: 2,
        name: 'typeB',
        Bs: [
            { id: 4, name: 'sample4', status: 'pending' }
        ]
    }
]

But the expected output should be something like

[
    {
        id: 1,
        name: 'typeA',
        Bs: [
            { id: 1, name: 'sample1', status: 'completed' },
            { id: 2, name: 'sample2', status: 'pending' },
            { id: 3, name: 'sample3', status: 'pending' }
        ]
    },
    {
        id: 2,
        name: 'typeB',
        Bs: [
            { id: 4, name: 'sample4', status: 'pending' }
        ]
    }
]

Basically get all instances of B related to A where any of the Bs has a status of pending.

来源:https://stackoverflow.com/questions/53923159/is-there-a-way-to-query-a-table-with-a-where-clause-on-a-related-table-but-still

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!