Skip to content

Commit

Permalink
fix(core): fix populating references for 1:m collections
Browse files Browse the repository at this point in the history
Closes #5336
  • Loading branch information
B4nan committed Mar 14, 2024
1 parent 9e35642 commit 9b9027d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/knex/src/AbstractSqlDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,7 @@ export abstract class AbstractSqlDriver<Connection extends AbstractSqlConnection
continue;
}

if (prop.kind === ReferenceKind.MANY_TO_MANY && ref) {
if ([ReferenceKind.ONE_TO_MANY, ReferenceKind.MANY_TO_MANY].includes(prop.kind) && ref) {
map[pk][propName] = [...map[pk][propName], ...(item[propName] as T[])];
continue;
}
Expand Down
58 changes: 58 additions & 0 deletions tests/features/collection/GH5336.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Collection, ManyToOne, OneToMany, Entity, MikroORM, PrimaryKey, Property } from '@mikro-orm/sqlite';

@Entity()
class User {

@PrimaryKey()
id!: number;

@Property()
name!: string;

@Property({ unique: true })
email!: string;

@OneToMany({ entity: () => Book, mappedBy: 'author' })
books = new Collection<Book>(this);

}

@Entity()
class Book {

@PrimaryKey()
id!: number;

@Property()
name!: string;

@ManyToOne({ entity: () => User })
author!: User;

}

let orm: MikroORM;

beforeAll(async () => {
orm = await MikroORM.init({
dbName: ':memory:',
entities: [User, Book],
});
await orm.schema.refreshDatabase();
});

afterAll(async () => {
await orm.close(true);
});

test('5336', async () => {
const author = orm.em.create(User, { name: 'Foo', email: 'foo' });
orm.em.create(Book, { name: 'Foo1', author });
orm.em.create(Book, { name: 'Foo2', author });
await orm.em.flush();

const user2 = await orm.em.fork().findOneOrFail(User, { name: 'Foo' }, { populate: ['books:ref'] });
const user1 = await orm.em.fork().findOneOrFail(User, { name: 'Foo' }, { populate: ['books'] });
expect(user1.books).toHaveLength(2);
expect(user2.books).toHaveLength(2);
});

0 comments on commit 9b9027d

Please sign in to comment.