如何使用TypeORM创建关系数据?

时间:2019-06-20 05:34:57

标签: node.js typescript express typeorm

我正在尝试创建和保存用户的产品。

这是我的尝试:

// userEntity.ts

import { Product } from '../product';

@Entity('user')
export class User {
  @PrimaryGeneratedColumn()
  id: number;

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

  @Column()
  password: string;

  @OneToMany(type => Product, product => product.user)
  @JoinTable()
  products: Product[];

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}
// productEntity.ts

import { ProductCategory } from './productCategoryEntity';
import { User } from '../user';

@Entity('product')
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @ManyToOne(type => ProductCategory, {
    eager: true,
    cascade: true
  })
  @JoinTable()
  category: ProductCategory;

  @ManyToOne(type => User, user => user.products)
  @JoinTable()
  user: User;

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

POSThttp://localhost:4000/users/1/products。这样可以成功创建产品,但与用户无关。

// userPost.ts

export async function userPostProduct(
  req: Request,
  res: Response,
  next: NextFunction
): Promise<void> {
  try {
    const userRepository: Repository<User> = getManager().getRepository(User);
    const productRepository: Repository<Product> = getManager().getRepository(
      Product
    );

    // Load user by id
    const user = await userRepository.findOne(req.params.id);

    const { ...data } = req.body;

    const productToBeSaved = new Product();
    productToBeSaved.name = data.name;
    productToBeSaved.shortDescription = data.shortDescription;
    productToBeSaved.longDescription = data.longDescription;
    productToBeSaved.price = data.price;
    productToBeSaved.category = data.category;
    if (user) {
      productToBeSaved.user = user;
    }

    // Validate product entity
    const errors: ValidationError[] = await validate(productToBeSaved, {
      skipMissingProperties: true
    }); // Errors is and array of validation errors

    if (errors.length > 0) {
      // Return BAD REQUEST status code
      return next(createError(400, errors));
    } else {
      let product = await productRepository.save(productToBeSaved);
      // Return a CREATED status code and new product
      res.status(201).send({
        message: 'Product saved successfully',
        product
      });
    }
  } catch (err) {
    // Return a BAD REQUEST status code and email already exists error
    return next(createError(400, err));
  }
}

我无法在1 GET下查询用户http://localhost:4000/users/1/products的产品

我也尝试过:

// Build up entity product to be saved
const productToBeSaved = productRepository.create(req.body);
productToBeSaved.user = user;

if (user) {
  user.products = [productToBeSaved];
  await userRepository.save(user);
}

..但它说productToBeSaved missing properties of Product[]: id, name, category, etc...

所以我改变了:

if (user) {
  user.products = [...productToBeSaved];
  await userRepository.save(user);
}

然后它说TypeError: productToBeSaved is not iterable

请帮助我,如何创建用户的产品关系。

技术堆栈:TypeScript,Express,PostgreSQL,TypeORM


我真的很想使用TypeORM,希望他们有更好的示例。

0 个答案:

没有答案