Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QueryBuilder update filtered by non-owning side of OneToOne mapping errors #4122

Closed
PenguinToast opened this issue Mar 11, 2023 · 1 comment
Labels
bug Something isn't working

Comments

@PenguinToast
Copy link
Contributor

Describe the bug
When using QueryBuilder.update on an entity filtered by the non-owning side of a self-referential OneToOne mapping, the generated query is missing a join or subquery. It will fail with an error similar to:

update `book` set `title` = 'updatedTitle' where `b1`.`id` is null - Unknown column 'b1.id' in 'where clause'

To Reproduce

import {
  Entity,
  Property,
  PrimaryKey,
  Ref,
  OneToOne,
  OptionalProps,
} from '@mikro-orm/core';
import { MikroORM } from '@mikro-orm/mysql';

@Entity()
export class Book {

  [OptionalProps]?: 'version';

  @PrimaryKey()
  id!: string;

  @OneToOne({ entity: () => Book, inversedBy: 'sequel', ref: true, nullable: true })
  prequel?: Ref<Book>;

  @OneToOne({ entity: () => Book, mappedBy: 'prequel', ref: true, nullable: true })
  sequel?: Ref<Book>;

  @Property()
  title!: string;

}

let orm: MikroORM;

beforeAll(async () => {
  orm = await MikroORM.init({
    dbName: 'mikro_orm_ghXXXX',
    entities: [Book],
    port: 3308,
    debug: true,
  });
  await orm.schema.refreshDatabase();
});

afterAll(() => orm.close(true));

test('unnamed', async () => {
  const book1 = orm.em.create(Book, { id: 'book1', title: 'book1' });
  const book2 = orm.em.create(Book, { id: 'book2', title: 'book2', prequel: 'book1' });
  await orm.em.persistAndFlush([book1, book2]);
  orm.em.clear();

  const qb = orm.em.createQueryBuilder(Book);
  // This line fails with `update `book` set `title` = 'updatedTitle' where `b1`.`id` is null - Unknown column 'b1.id' in 'where clause'`
  await qb.update({ title: 'updatedTitle' }).where({ sequel: null });

  await orm.em.refresh(book1);
  await orm.em.refresh(book2);
  expect(book1.title).toEqual('book1');
  expect(book2.title).toEqual('updatedTitle');
});

Expected behavior
The generated update query should either include a subquery or join on the table.

Versions
5.6.13 (and latest master)

Dependency Version
node 18.5.0
typescript 4.9.0
mikro-orm 5.6.13
@B4nan B4nan added the bug Something isn't working label Mar 12, 2023
@B4nan B4nan closed this as completed in 0a053fe Mar 12, 2023
@PenguinToast
Copy link
Contributor Author

Amazing, thanks for the quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants