Merge pull request #3515 from payloadcms/fix/#3513

fix: #3513, hasMany relationships unable to be cleared
This commit is contained in:
James Mikrut
2023-10-09 13:47:34 -04:00
committed by GitHub
3 changed files with 44 additions and 2 deletions

View File

@@ -215,7 +215,19 @@ export const traverseFields = <T extends Record<string, unknown>>({
if (field.type === 'relationship' || field.type === 'upload') {
const relationPathMatch = relationships[`${sanitizedPath}${field.name}`]
if (!relationPathMatch) return result
if (!relationPathMatch) {
if ('hasMany' in field && field.hasMany) {
if (field.localized && config.localization && config.localization.locales) {
result[field.name] = {
[config.localization.defaultLocale]: [],
}
} else {
result[field.name] = []
}
}
return result
}
if (field.localized) {
result[field.name] = {}

View File

@@ -335,7 +335,7 @@ export const traverseFields = ({
})
}
} else {
if (fieldData === null) {
if (fieldData === null || (Array.isArray(fieldData) && fieldData.length === 0)) {
relationshipsToDelete.push({ path: relationshipPath })
return
}

View File

@@ -434,6 +434,36 @@ describe('Relationships', () => {
expect(director.docs[0].movies.length).toBeGreaterThan(10)
})
it('should allow clearing hasMany relationships', async () => {
const fiveMovies = await payload.find({
collection: 'movies',
limit: 5,
depth: 0,
})
const movieIDs = fiveMovies.docs.map((doc) => doc.id)
const stanley = await payload.create({
collection: 'directors',
data: {
name: 'Stanley Kubrick',
movies: movieIDs,
},
})
expect(stanley.movies).toHaveLength(5)
const stanleyNeverMadeMovies = await payload.update({
collection: 'directors',
id: stanley.id,
data: {
movies: null,
},
})
expect(stanleyNeverMadeMovies.movies).toHaveLength(0)
})
})
})
})