fix: import with associations (#6024)

* fix: import with associations

* chore: console.log
This commit is contained in:
ChengLei Shao 2025-01-09 09:19:02 +08:00 committed by GitHub
parent 3c83c1b9cd
commit ec92727a20
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 94 additions and 2 deletions

View File

@ -19,7 +19,7 @@ export class ToManyInterface extends BaseInterface {
const items = str.split(',');
const { filterKey, targetCollection, transaction } = ctx;
const { filterKey, targetCollection, transaction, field } = ctx;
const targetInstances = await targetCollection.repository.find({
filter: {
@ -36,7 +36,19 @@ export class ToManyInterface extends BaseInterface {
});
const primaryKeyAttribute = targetCollection.model.primaryKeyAttribute;
const targetKey = field.options.targetKey;
return targetInstances.map((targetInstance) => targetInstance[primaryKeyAttribute]);
const values = targetInstances.map((targetInstance) => {
const result = {
[targetKey]: targetInstance[targetKey],
};
if (targetKey !== primaryKeyAttribute) {
result[primaryKeyAttribute] = targetInstance[primaryKeyAttribute];
}
return result;
});
return values;
}
}

View File

@ -1739,4 +1739,84 @@ describe('xlsx importer', () => {
expect(await User.repository.count()).toBe(0);
expect(error).toBeTruthy();
});
it('should import with associations by target key', async () => {
const Post = app.db.collection({
name: 'posts',
fields: [
{
name: 'title',
type: 'string',
},
{
name: 'tags',
type: 'belongsToMany',
through: 'post_tag',
targetKey: 'name',
interface: 'm2m',
},
],
});
const Tag = app.db.collection({
name: 'tags',
fields: [
{
name: 'name',
type: 'string',
unique: true,
},
],
});
await app.db.sync();
await Tag.repository.create({
values: {
name: 't1',
},
});
const templateCreator = new TemplateCreator({
collection: Post,
columns: [
{
dataIndex: ['title'],
defaultTitle: '标题',
},
{
dataIndex: ['tags', 'name'],
defaultTitle: 'TagsName',
},
],
});
const template = await templateCreator.run();
const worksheet = template.Sheets[template.SheetNames[0]];
XLSX.utils.sheet_add_aoa(worksheet, [['Post1', 't1']], {
origin: 'A2',
});
const importer = new XlsxImporter({
collectionManager: app.mainDataSource.collectionManager,
collection: Post,
columns: [
{
dataIndex: ['title'],
defaultTitle: '标题',
},
{
dataIndex: ['tags', 'name'],
defaultTitle: 'TagsName',
},
],
workbook: template,
});
await importer.run();
expect(await Post.repository.count()).toBe(1);
});
});