diff --git a/packages/pinia-orm/src/query/Query.ts b/packages/pinia-orm/src/query/Query.ts index ace6503d4..49d86989f 100644 --- a/packages/pinia-orm/src/query/Query.ts +++ b/packages/pinia-orm/src/query/Query.ts @@ -402,8 +402,17 @@ export class Query { const data = this.commit('all') const collection = [] as Collection - for (const id in data) { - if (ids === undefined || ids.length === 0 || ids.includes(id)) { collection.push(this.hydrate(data[id], { visible: this.visible, hidden: this.hidden, operation: 'get' })) } + const deduplicatedIds = new Set(ids) + + if (deduplicatedIds.size > 0) { + deduplicatedIds.forEach((id) => { + if (data[id]) + collection.push(this.hydrate(data[id], { visible: this.visible, hidden: this.hidden, operation: 'get' })) + }) + } + else { + Object.values(data) + .forEach((value: any) => collection.push(this.hydrate(value, { visible: this.visible, hidden: this.hidden, operation: 'get' }))) } return collection @@ -478,10 +487,18 @@ export class Query { /** * Retrieve models by processing all filters set to the query chain. */ - select (): Collection { - const whereIds = this.wheres.find(where => where.field === this.model.$getKeyName())?.value + + select(): Collection { let ids: string[] = [] - if (whereIds) { ids = ((isFunction(whereIds) ? [] : isArray(whereIds) ? whereIds : [whereIds]) || []).map(String) || [] } + // store the original wheres so multiple selects don't alter the result + const originalWheres = this.wheres + const whereIdsIndex = this.wheres.findIndex(where => where.field === this.model.$getKeyName()) + if (whereIdsIndex > -1) { + const whereIds = this.wheres[whereIdsIndex].value + ids = ((isFunction(whereIds) ? [] : isArray(whereIds) ? whereIds : [whereIds]) || []).map(String) || [] + if (ids.length > 0) + this.wheres = [...this.wheres.slice(0, whereIdsIndex), ...this.wheres.slice(whereIdsIndex + 1)] + } let models = this.storeFind(ids) @@ -489,6 +506,8 @@ export class Query { models = this.filterOrder(models) models = this.filterLimit(models) + this.wheres = originalWheres + return models } diff --git a/packages/pinia-orm/tests/feature/repository/retrieves_find.spec.ts b/packages/pinia-orm/tests/feature/repository/retrieves_find.spec.ts index 2bcfba137..03511ae6d 100644 --- a/packages/pinia-orm/tests/feature/repository/retrieves_find.spec.ts +++ b/packages/pinia-orm/tests/feature/repository/retrieves_find.spec.ts @@ -102,4 +102,24 @@ describe('feature/repository/retrieves_find', () => { { id: 3, name: 'Johnny Doe' } ]) }) + + it('can find records with composite key', () => { + class UserComposite extends Model { + static entity = 'user_composites'; + static primaryKey = ['id', 'secondId']; + @Attr(null) declare id: number; + @Attr(null) declare secondId: number; + } + + const userRepo = useRepo(UserComposite) + + userRepo.save({ + id: 1, + secondId: 2, + }); + + const user = userRepo.find('[1,2]') + + expect(user).not.toBe(null) + }) })