feat: support where querying by join fields (#12075)
### What?
This PR adds support for `where` querying by the join field (don't
confuse with `where` querying of related docs via `joins.where`)
Previously, this didn't work:
```
const categories = await payload.find({
collection: 'categories',
where: { 'relatedPosts.title': { equals: 'my-title' } },
})
```
### Why?
This is crucial for bi-directional relationships, can be used for access
control.
### How?
Implements `where` handling for join fields the same as we do for
relationships. In MongoDB it's not as efficient as it can be, the old PR
that improves it and can be updated later is here
https://github.com/payloadcms/payload/pull/8858
Fixes https://github.com/payloadcms/payload/discussions/9683
This commit is contained in:
@@ -1459,6 +1459,51 @@ describe('Joins Field', () => {
|
||||
expect(parent.children?.totalDocs).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('should support where querying by a top level join field', async () => {
|
||||
const category = await payload.create({ collection: 'categories', data: {} })
|
||||
await payload.create({
|
||||
collection: 'posts',
|
||||
data: { category: category.id, title: 'my-title' },
|
||||
})
|
||||
const found = await payload.find({
|
||||
collection: 'categories',
|
||||
where: { 'relatedPosts.title': { equals: 'my-title' } },
|
||||
})
|
||||
|
||||
expect(found.docs).toHaveLength(1)
|
||||
expect(found.docs[0].id).toBe(category.id)
|
||||
})
|
||||
|
||||
it('should support where querying by a join field with hasMany relationship', async () => {
|
||||
const category = await payload.create({ collection: 'categories', data: {} })
|
||||
await payload.create({
|
||||
collection: 'posts',
|
||||
data: { categories: [category.id], title: 'my-title' },
|
||||
})
|
||||
|
||||
const found = await payload.find({
|
||||
collection: 'categories',
|
||||
where: { 'hasManyPosts.title': { equals: 'my-title' } },
|
||||
})
|
||||
expect(found.docs).toHaveLength(1)
|
||||
expect(found.docs[0].id).toBe(category.id)
|
||||
})
|
||||
|
||||
it('should support where querying by a join field with relationship nested to a group', async () => {
|
||||
const category = await payload.create({ collection: 'categories', data: {} })
|
||||
await payload.create({
|
||||
collection: 'posts',
|
||||
data: { group: { category: category.id }, title: 'my-category-title' },
|
||||
})
|
||||
const found = await payload.find({
|
||||
collection: 'categories',
|
||||
where: { 'group.relatedPosts.title': { equals: 'my-category-title' } },
|
||||
})
|
||||
|
||||
expect(found.docs).toHaveLength(1)
|
||||
expect(found.docs[0].id).toBe(category.id)
|
||||
})
|
||||
})
|
||||
|
||||
async function createPost(overrides?: Partial<Post>, locale?: Config['locale']) {
|
||||
|
||||
Reference in New Issue
Block a user