Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,10 @@ export class Collection<Schema extends StandardSchemaV1> {
* Deletes all the records in this collection.
*/
public clear(): void {
for (const record of this.#records) {
this.#deleteRecord(record)
}

this.#records.length = 0
}

Expand Down
24 changes: 24 additions & 0 deletions tests/relations/one-to-many.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,30 @@ it('cascades foreign record deletion when the owner record is deleted', async ()
expect(users.all()).toEqual([])
})

it('cascades foreign record deletion when clearing the entire collection', async () => {
const users = new Collection({ schema: userSchema })
const posts = new Collection({ schema: postSchema })

users.defineRelations(({ many }) => ({
posts: many(posts),
}))
posts.defineRelations(({ one }) => ({
// When the referenced author is deleted, delete all their posts.
author: one(users, { onDelete: 'cascade' }),
}))

const post = await posts.create({ title: 'First' })
const user = await users.create({
id: 1,
posts: [post],
})

users.clear()

expect(posts.all()).toEqual([])
expect(users.all()).toEqual([])
})

it('supports unique one-to-many relations', async () => {
const users = new Collection({ schema: userSchema })
const posts = new Collection({ schema: postSchema })
Expand Down