Merge pull request #3515 from payloadcms/fix/#3513
fix: #3513, hasMany relationships unable to be cleared
This commit is contained in:
@@ -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] = {}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user