TypeORM - 更新多对多关系引发列不存在错误

Tim*_*Tim 5 javascript node.js typeorm

我有一个可以包含多个产品的用户实体。当我用新产品更新我的用户实体时,会抛出以下错误:column "userId" of relation "user" does not exist. 我不知道实体中的userId列user来自哪里。当我跳过更新产品时,一切正常。我已经尝试掺杂并重新创建所有表,并且还添加了双向关系,product.ts但错误仍然存​​在。经过长时间的搜索,我仍然不知道我的错误在哪里。

我的实体:

User.ts

import {
  BaseEntity,
  Entity,
  Column,
  PrimaryGeneratedColumn,
  OneToOne,
  ManyToMany,
  JoinColumn,
  JoinTable,
  BeforeInsert,
  BeforeUpdate,
  Unique,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  Index,
} from 'typeorm';
import { hash } from 'argon2';
import Type from './Type';
import Address from './Address';
import Product from './Product';

export enum UserRoles {
  GAST,
  ANBIETER,
  MODERATOR,
  ADMIN,
}

@Entity()
@Unique(['email'])
export default class User extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 100, nullable: true })
  displayName: string;

  @Index()
  @Column({ unique: true, length: 256 })
  email: string;

  @Column({ select: false })
  password: string;

  @ManyToOne(() => Type)
  @JoinColumn()
  type: Type;

  @Column({
    type: 'enum',
    enum: UserRoles,
    default: UserRoles.GAST,
  })
  role: UserRoles;

  @OneToOne(() => Address, { nullable: true })
  @JoinColumn()
  address: Address;

  @Column({ nullable: true })
  website: string;

  @Column({ nullable: true })
  phoneNumber: string;

  @Column({ length: 250, nullable: true })
  description: string;

  @Column({ length: 250, nullable: true })
  notes: string;

  @Column({ default: false })
  verified: boolean;

  @Column({ default: true })
  visible: boolean;

  @ManyToMany(() => Product)
  @JoinTable({ name: 'user_products' })
  products: Product[];

  // https://github.com/typeorm/typeorm/issues/2651
  @CreateDateColumn({ update: false })
  createdAt: Date;

  @UpdateDateColumn({ update: false })
  updatedAt: Date;

  @BeforeInsert()
  @BeforeUpdate()
  async hashPassword() {
    if (this.password && !this.password.startsWith('$argon2')) {
      this.password = await hash(this.password);
    }
  }

  static findByEmailWithPassord(email: string): Promise<User> {
    return this.createQueryBuilder('user')
      .where('user.email = :email', { email })
      .addSelect('user.password')
      .getOne();
  }
}
Run Code Online (Sandbox Code Playgroud)

Product.ts

import {
  BaseEntity,
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

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

  @Column({ length: 100 })
  name: string;

  // https://github.com/typeorm/typeorm/issues/2651
  @CreateDateColumn({ update: false })
  createdAt: Date;

  @UpdateDateColumn({ update: false })
  updatedAt: Date;
}

Run Code Online (Sandbox Code Playgroud)

更新例程:

const updateUser: User = await User.findOne(userId, {
  relations: ['address', 'products'],
});

updateUser.displayName = req.body.displayName;
updateUser.email = req.body.email;
updateUser.website = req.body.website;
updateUser.phoneNumber = req.body.phoneNumber;
updateUser.description = req.body.description;
updateUser.visible = req.body.visible;

if (req.body.address) {
  const address: Address = updateUser.address || new Address();
  address.company = req.body.address.company;
  address.address1 = req.body.address.address1;
  address.address2 = req.body.address.address2;
  address.address3 = req.body.address.address3;
  address.code = req.body.address.code;
  address.city = req.body.address.city;
  address.state = req.body.address.state;
  address.country = req.body.address.country;

  if (!updateUser.address) {
    await address.save();
  } else {
    await Address.update(address.id, address);
  }

  updateUser.address = address;
}

if (req.body.products) {
  const products = await Product.find({
    where: {
      id: In(req.body.products),
    },
  });

  updateUser.products = req.body.products; // when removing this everything works fine
}

await User.update(userId, updateUser);
Run Code Online (Sandbox Code Playgroud)

抛出此错误:

message: column "userId" of relation "user" does not exist
name: QueryFailedError
code: 42703
file: analyze.c
line: 2333
routine: transformUpdateTargetList
query:
UPDATE "user"
SET "id"          = $2,
    "displayName" = $3,
    "email"       = $4,
    "role"        = $5,
    "website"     = $6,
    "phoneNumber" = $7,
    "description" = $8,
    "notes"       = $9,
    "verified"    = $10,
    "visible"     = $11,
    "addressId"   = $12,
    "userId"      = $13, -- where does this come from?
    "updatedAt"   = CURRENT_TIMESTAMP
WHERE "id" IN ($1)
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 6

答案比我想象的简单得多,我只需要运行await updateUser.save();而不是await User.update(userId, updateUser);. 我不知道我为什么这样做。