typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
34.22k stars 6.31k forks source link

OneToMany - ManyToOne create null foreign keys #8367

Open TheBous opened 2 years ago

TheBous commented 2 years ago

Issue Description

Expected Behavior

When I create a relation OneToMany - ManyToOne between 2 entities I expect to find a valorized foreign key in the ManyToOne table.

Actual Behavior

In the actual behaviour, the row is inserted but with FK = null;

@Entity()
export class Account extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true })
  apikey: string;

  @Column({ unique: true })
  apikeysecret: string;

  @Column()
  @CreateDateColumn()
  createdAt: Date;

  @Column()
  @UpdateDateColumn()
  updatedAt: Date;

  @Column()
  exchange: string;

  @ManyToOne(() => User, (user: User) => user.accountsaccounts, {
    onUpdate: 'CASCADE',
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'userid', referencedColumnName: 'id' })
  public useruser: User;
}
@Entity()
export class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany(() => Account, (account: Account) => account.useruser, {
    eager: true,
    cascade: true,
  })
  accountsaccounts: Account[];

  @BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    this.password = await bcrypt.hash(this.password, 8);
  }

  async validatePassword(password: string): Promise<boolean> {
    return bcrypt.compare(password, this.password);
  }
}
async create(createAccountDto: CreateAccountDto, user: User) {
    const { apikey, apikeysecret, exchange } = createAccountDto;
    if (await this.findByApikeyAndSecret(apikey, apikeysecret)) {
      throw new HttpException(
        'Account with these api key and api key secret already exists',
        HttpStatus.UNPROCESSABLE_ENTITY,
      );
    }

    const account = new Account();
    account.apikey = apikey;
    account.apikeysecret = apikeysecret;
    account.exchange = exchange;
    account.useruser = user;

    await this.accountRepository.save(account);
  }

Steps to Reproduce

You only need to create 2 entities like above and try to insert a row in Account table.

My Environment

NodeJS 16, NestJS 8, TypeORM 0.2.40

Are you willing to resolve this issue by submitting a Pull Request?

ganshiqingyuan commented 2 years ago

many-to-one don't need @JoinColumn

TheBous commented 2 years ago

Even if i remove @JoinColumn, it does not work :(

ganshiqingyuan commented 2 years ago

Even if i remove @joincolumn, it does not work :(

not set cascade: true at Many-to-one in Account

ghost commented 2 years ago

I have the same problem, any way to solve this?

Martijncvv commented 1 year ago

Where you able to fix it? Same problem

inane commented 1 year ago

Any new about this topic? same problem