首页 > 解决方案 > Typeorm 中的关系

问题描述

我有一个数据库,其结构如下所示:

类别表

import { productsEntity } from "src/products/entity/products.entity";
import { BaseEntity, Column, Entity, ManyToMany, PrimaryGeneratedColumn } from "typeorm";

@Entity('categories')
export class category extends BaseEntity{
    @PrimaryGeneratedColumn()
    id: number;

    @Column({nullable: false, default: 'all', unique: true})
    title: string;

    @ManyToMany(()=> productsEntity, product => product.categories)
    products: productsEntity[]
}

产品表

  import { category } from "src/products/entity/category.entity";
    import { BaseEntity, Column, CreateDateColumn, Entity, JoinColumn, JoinTable, ManyToMany, ManyToOne, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";
    
    @Entity('products')
    export class productsEntity extends BaseEntity{
        @PrimaryGeneratedColumn()
        id: number;
    
       //.... Columns
   
        @ManyToMany(() => category, categories => categories.products, {cascade: true})
        @JoinTable({name: 'product_category'})
        categories: category[];
    
    }

这两个表都具有多对多关系。当我创建这样的新产品时:

 async addProduct(productDetails){
        const {title, description, belongsTo, price, units}  = productDetails;
        let newProduct = new productsEntity();
        newProduct.title = title;
        newProduct.description = description;
        newProduct.price = price;
        newProduct.units = units;
        newProduct.categories = [belongsTo];
        newProduct.save();
    }
}

它保存运行此查询的所有字段:

INSERT INTO "products"("title", "description", "price", "units", "created_at", "updated_at") VALUES ($1, $2, $3, $4, DEFAULT, DEFAULT) RETURNING "id", "created_at", "updated_at"

但不是在类别中,新的中间表也没有更新。我究竟做错了什么??

标签: javascriptnode.jsdatabasetypescripttypeorm

解决方案


推荐阅读