fix: load association field in collection (#4122)

* fix: load association field in collection

* chore: test
This commit is contained in:
ChengLei Shao 2024-04-22 10:28:34 +08:00 committed by GitHub
parent 15325101d6
commit e8cf01a99d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 59 additions and 0 deletions

View File

@ -189,4 +189,53 @@ describe('load collections', function () {
expect(groups[0].users.length).toBe(1);
});
it('should load has one association', async () => {
await collectionRepository.create({
values: {
name: 'profiles',
fields: [{ name: 'id', type: 'bigInt', primaryKey: true, autoIncrement: true }],
},
context: {},
});
await fieldsRepository.create({
values: { type: 'string', name: 'userCode', collectionName: 'profiles' },
context: {},
});
await collectionRepository.create({
values: {
name: 'users',
fields: [
{ name: 'id', type: 'bigInt', primaryKey: true, autoIncrement: true },
{ name: 'name', type: 'string' },
],
},
context: {},
});
await fieldsRepository.create({
values: { type: 'string', name: 'userCode', collectionName: 'users' },
context: {},
});
await fieldsRepository.create({
values: {
type: 'hasOne',
name: 'profile',
foreignKey: 'userCode',
sourceKey: 'userCode',
collectionName: 'users',
target: 'profiles',
},
context: {},
});
await app.runCommand('restart');
db = app.db;
const User = db.getCollection('users');
expect(User.model.associations['profile']).toBeTruthy();
});
});

View File

@ -112,6 +112,16 @@ export class CollectionModel extends MagicAttributeModel {
// @ts-ignore
const instances: FieldModel[] = fields;
instances.sort((a, b) => {
if (a.isAssociationField() && !b.isAssociationField()) {
return 1;
}
if (!a.isAssociationField() && b.isAssociationField()) {
return -1;
}
return 0;
});
for (const instance of instances) {
await instance.load(options);
}