Skip to content

Commit 5b97ac1

Browse files
authored
fix: querying relationships by id path with REST (#9013)
### What? Fixes the issue with querying by `id` from REST / `overrideAccess: false`. For example, this didn't work: `/api/loans?where[book.bibliography.id][equals]=67224d74257b3f2acddc75f4` ``` QueryError: The following path cannot be queried: id ``` ### Why? We support this syntax within the Local API. ### How? Now, for simplicity we sanitize everything like `relation.otherRelation.id` to `relation.otherRelation` Fixes #9008
1 parent f10a160 commit 5b97ac1

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

packages/payload/src/database/queryValidation/validateSearchParams.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ export async function validateSearchParam({
7373
})
7474
}
7575
const promises = []
76+
77+
// Sanitize relation.otherRelation.id to relation.otherRelation
78+
if (paths.at(-1)?.path === 'id') {
79+
const previousField = paths.at(-2)?.field
80+
if (
81+
previousField &&
82+
(previousField.type === 'relationship' || previousField.type === 'upload') &&
83+
typeof previousField.relationTo === 'string'
84+
) {
85+
paths.pop()
86+
}
87+
}
88+
7689
promises.push(
7790
...paths.map(async ({ collectionSlug, field, invalid, path }, i) => {
7891
if (invalid) {
@@ -115,6 +128,7 @@ export async function validateSearchParam({
115128
) {
116129
fieldPath = fieldPath.replace('.value', '')
117130
}
131+
118132
const entityType: 'collections' | 'globals' = globalConfig ? 'globals' : 'collections'
119133
const entitySlug = collectionSlug || globalConfig.slug
120134
const segments = fieldPath.split('.')

test/relationships/int.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,35 @@ describe('Relationships', () => {
875875
expect(query.docs[0].id).toStrictEqual(firstLevelID)
876876
})
877877

878+
it('should allow querying on id two levels deep', async () => {
879+
const query = await payload.find({
880+
collection: 'chained',
881+
where: {
882+
'relation.relation.id': {
883+
equals: thirdLevelID,
884+
},
885+
},
886+
})
887+
888+
expect(query.docs).toHaveLength(1)
889+
expect(query.docs[0].id).toStrictEqual(firstLevelID)
890+
891+
const queryREST = await restClient
892+
.GET(`/chained`, {
893+
query: {
894+
where: {
895+
'relation.relation.id': {
896+
equals: thirdLevelID,
897+
},
898+
},
899+
},
900+
})
901+
.then((res) => res.json())
902+
903+
expect(queryREST.docs).toHaveLength(1)
904+
expect(queryREST.docs[0].id).toStrictEqual(firstLevelID)
905+
})
906+
878907
it('should allow querying within array nesting', async () => {
879908
const page = await payload.create({
880909
collection: 'pages',

0 commit comments

Comments
 (0)