Skip to content

Commit

Permalink
fix(core): fix querying by embedded properties inside relations
Browse files Browse the repository at this point in the history
Closes #5391
  • Loading branch information
B4nan committed Apr 8, 2024
1 parent 2b45717 commit 2e74699
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/knex/src/query/QueryBuilderHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,13 @@ export class QueryBuilderHelper {
} else {
const [a, ...rest] = field.split('.');
const f = rest.join('.');
ret = a + '.' + this.fieldName(f, a, always, idx);
const fieldName = this.fieldName(f, a, always, idx) as string | RawQueryFragment;

if (fieldName instanceof RawQueryFragment) {
return fieldName.sql;
}

ret = a + '.' + fieldName;
}

if (quote) {
Expand Down
100 changes: 100 additions & 0 deletions tests/features/embeddables/GH5391.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { Embeddable, Embedded, Entity, ManyToOne, MikroORM, PrimaryKey, Property, Ref } from '@mikro-orm/libsql';

@Embeddable()
class RoleMeta {

@Property()
testString!: string;

}

@Entity()
class Role {

@PrimaryKey()
id!: number;

@Property()
name!: string;

@Embedded({ entity: () => RoleMeta, nullable: true, object: true })
meta?: RoleMeta;

}

@Entity()
class User {

@PrimaryKey()
id!: number;

@Property()
name!: string;

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

@ManyToOne(() => Role, { ref: true })
role!: Ref<Role>;

}

let orm: MikroORM;

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

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

test('Fetching an entity by a field in embeddable of a relation - does not work', async () => {
orm.em.create(Role, { name: 'Foo', meta: { testString: 'test' } });
await orm.em.flush();
orm.em.clear();

const role = await orm.em.findOneOrFail(Role, { name: 'Foo' });
orm.em.create(User, { name: 'Foo', email: 'foo', role });
await orm.em.flush();
orm.em.clear();

const user = await orm.em.findOneOrFail(User, {
email: 'foo',
role: {
meta: {
testString: 'test',
},
},
});
expect(user.name).toBe('Foo');
user.name = 'Bar';
orm.em.remove(user);
await orm.em.flush();

const count = await orm.em.count(User, { email: 'foo' });
expect(count).toBe(0);
});

test('Fetching an entity by a field in embeddable - working', async () => {
orm.em.create(Role, { name: 'Foo1', meta: { testString: 'test1' } });
await orm.em.flush();
orm.em.clear();

const role = await orm.em.findOneOrFail(Role, {
meta: {
testString: 'test1',
},
});

expect(role.name).toBe('Foo1');
orm.em.remove(role);
await orm.em.flush();

const count = await orm.em.count(Role, { name: 'Foo1' });
expect(count).toBe(0);
});

0 comments on commit 2e74699

Please sign in to comment.