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
29 changes: 24 additions & 5 deletions packages/pinia-orm/src/query/Query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,17 @@ export class Query<M extends Model = Model> {
const data = this.commit('all')
const collection = [] as Collection<M>

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
Expand Down Expand Up @@ -478,17 +487,27 @@ export class Query<M extends Model = Model> {
/**
* Retrieve models by processing all filters set to the query chain.
*/
select (): Collection<M> {
const whereIds = this.wheres.find(where => where.field === this.model.$getKeyName())?.value

select(): Collection<M> {
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)

models = this.filterWhere(models)
models = this.filterOrder(models)
models = this.filterLimit(models)

this.wheres = originalWheres

return models
}

Expand Down
20 changes: 20 additions & 0 deletions packages/pinia-orm/tests/feature/repository/retrieves_find.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})