fix: support hasMany: true relationships in findDistinct (#13840)

Previously, the `findDistinct` operation didn't work correctly for
relationships with `hasMany: true`. This PR fixes it.
This commit is contained in:
Sasha
2025-09-17 18:21:24 +03:00
committed by GitHub
parent a26d8d9554
commit d0543a463f
6 changed files with 139 additions and 21 deletions

View File

@@ -126,6 +126,12 @@ export const getConfig: () => Partial<Config> = () => ({
relationTo: 'categories',
name: 'category',
},
{
type: 'relationship',
relationTo: 'categories',
hasMany: true,
name: 'categories',
},
{
type: 'relationship',
relationTo: 'categories-custom-id',

View File

@@ -856,6 +856,75 @@ describe('database', () => {
}
})
it('should populate distinct relationships of hasMany: true when depth>0', async () => {
await payload.delete({ collection: 'posts', where: {} })
await payload.delete({ collection: 'categories', where: {} })
const categories = ['category-1', 'category-2', 'category-3', 'category-4'].map((title) => ({
title,
}))
const categoriesIDS: { categories: string }[] = []
for (const { title } of categories) {
const doc = await payload.create({ collection: 'categories', data: { title } })
categoriesIDS.push({ categories: doc.id })
}
await payload.create({
collection: 'posts',
data: {
title: '1',
categories: [categoriesIDS[0]?.categories, categoriesIDS[1]?.categories],
},
})
await payload.create({
collection: 'posts',
data: {
title: '2',
categories: [
categoriesIDS[0]?.categories,
categoriesIDS[2]?.categories,
categoriesIDS[3]?.categories,
],
},
})
await payload.create({
collection: 'posts',
data: {
title: '3',
categories: [
categoriesIDS[0]?.categories,
categoriesIDS[3]?.categories,
categoriesIDS[1]?.categories,
],
},
})
const resultDepth0 = await payload.findDistinct({
collection: 'posts',
sort: 'categories.title',
field: 'categories',
})
expect(resultDepth0.values).toStrictEqual(categoriesIDS)
const resultDepth1 = await payload.findDistinct({
depth: 1,
collection: 'posts',
field: 'categories',
sort: 'categories.title',
})
for (let i = 0; i < resultDepth1.values.length; i++) {
const fromRes = resultDepth1.values[i] as any
const id = categoriesIDS[i].categories as any
const title = categories[i]?.title
expect(fromRes.categories.title).toBe(title)
expect(fromRes.categories.id).toBe(id)
}
})
describe('Compound Indexes', () => {
beforeEach(async () => {
await payload.delete({ collection: 'compound-indexes', where: {} })

View File

@@ -197,6 +197,7 @@ export interface Post {
id: string;
title: string;
category?: (string | null) | Category;
categories?: (string | Category)[] | null;
categoryCustomID?: (number | null) | CategoriesCustomId;
localized?: string | null;
text?: string | null;
@@ -822,6 +823,7 @@ export interface CategoriesCustomIdSelect<T extends boolean = true> {
export interface PostsSelect<T extends boolean = true> {
title?: T;
category?: T;
categories?: T;
categoryCustomID?: T;
localized?: T;
text?: T;