Skip to content

Commit

Permalink
fix(core): map virtual properties that shadow a regular property from…
Browse files Browse the repository at this point in the history
… joined results

Closes #4764
  • Loading branch information
B4nan committed Sep 30, 2023
1 parent f4868ed commit d0b3698
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
11 changes: 11 additions & 0 deletions packages/knex/src/AbstractSqlDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,17 @@ export abstract class AbstractSqlDriver<Connection extends AbstractSqlConnection
return;
}

meta2.props
.filter(prop => prop.persist === false)
.forEach(prop => {
if (prop.fieldNames.length > 1) { // composite keys
relationPojo[prop.name] = prop.fieldNames.map(name => root![`${relationAlias}__${name}`]);
} else {
const alias = `${relationAlias}__${prop.fieldNames[0]}`;
relationPojo[prop.name] = root![alias];
}
});

meta2.props
.filter(prop => this.platform.shouldHaveColumn(prop, p.children || []))
.forEach(prop => {
Expand Down
60 changes: 60 additions & 0 deletions tests/issues/GH3820.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Collection, Entity, LoadStrategy, ManyToOne, PrimaryKey, Property, ManyToMany } from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/sqlite';

@Entity()
class Account {

@PrimaryKey()
id!: number;

@ManyToOne(() => Account, { nullable: true })
parent!: Account | null;

@Property({ persist: false })
parentId!: number | null;

@ManyToMany(() => User, user => user.accounts)
users = new Collection<User>(this);

}

@Entity()
class User {

@PrimaryKey()
id!: number;

@ManyToMany(() => Account)
accounts = new Collection<Account>(this);

}

let orm: MikroORM;

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

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

test(`relations' orderBy should be respected when using LoadStrategy.JOINED`, async () => {
const a = await orm.em.insert(Account, { id: 1 });
const b = await orm.em.insert(Account, { id: 2, parent: a });
const u = await orm.em.insert(User, { id: 11, accounts: [1, 2] });
const r1 = await orm.em.fork().findOneOrFail(User, { id: 11 }, { populate: ['accounts'], strategy: LoadStrategy.SELECT_IN });
expect(r1.accounts.$[0].parent).toBe(null);
expect(r1.accounts.$[0].parentId).toBe(null);
expect(r1.accounts.$[1].parent?.id).toBe(1);
expect(r1.accounts.$[1].parentId).toBe(1);
const r2 = await orm.em.fork().findOneOrFail(User, { id: 11 }, { populate: ['accounts'], strategy: LoadStrategy.JOINED });
expect(r2.accounts.$[0].parent).toBe(null);
expect(r2.accounts.$[0].parentId).toBe(null);
expect(r2.accounts.$[1].parent?.id).toBe(1);
expect(r2.accounts.$[1].parentId).toBe(1);
});

0 comments on commit d0b3698

Please sign in to comment.