问题
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