我正在尝试保存具有许多类别的产品。同时,一个类别可以有许多产品。因此,我认为最好的解决方案是对数据进行建模的ManyToMany关系。
当我尝试创建新产品时,发生错误,提示无法插入具有空值的新类别。疯狂的是,我不需要创建新类别,而是想要采用现有类别并将其分配给新产品。
这是控制台返回的SQL消息:
SQLITE_CONSTRAINT: NOT NULL constraint failed: category.name',
errno: 19,
code: 'SQLITE_CONSTRAINT',
name: 'QueryFailedError',
query: 'INSERT INTO "category"("id", "parent_id", "name", "description", "createdAt", "updatedAt") VALUES (NULL, NULL, NULL, NULL, datetime(\'now\'), datetime(\'now\'))
按照 typeorm documentation example ,我推断我的代码必须类似于下一个:
Product.ts
@Entity()
@Unique(["code"])
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column({
length: 20
})
code: string;
@Column({
length: 100
})
name: string;
@Column()
description: string;
@Column()
stock: number;
@Column({
type: "real"
})
price: number;
@Column()
public_price: boolean;
@Column()
public: boolean;
@ManyToMany(type => Category, category => category.products, {
cascade: true
})
@JoinTable()
categories: Category[];
}
Category.ts
@Entity()
export class Category {
@PrimaryGeneratedColumn()
id: number;
@Column({ nullable: true })
parent_id: number;
@Column()
@IsNotEmpty()
name: string;
@Column()
description?: string;
@Column()
@CreateDateColumn()
createdAt: Date;
@Column()
@UpdateDateColumn()
updatedAt: Date;
@ManyToMany(type => Product, product => product.categories)
products: Product[];
}
ProductController.ts(创建方法)
static create = async (req: Request, res: Response) => {
const { categories, ...data } = req.body
const categoryRepository = getRepository(Category);
const productRepository = getRepository(Product);
const cats = []
for (const id of categories) {
const cat = await categoryRepository.find(id)
cats.push(cat)
}
const product = new Product();
for (const index in data) {
product[index] = data[index]
}
product.categories = cats
try {
await productRepository.save(product);
res.send('Product successfuly created');
} catch (err) {
console.log(err)
res.status(409).send('Error on product creation');
}
}
这是我用来通过Postman测试我的应用程序的JSON对象:
{
"code": "1234",
"name": "TESTING PRODUCT CREATION",
"description": "Product sended through postman",
"stock": "99",
"price": "255.88",
"public_price": true,
"public": true,
"categories": [1]
}
答案 0 :(得分:1)
替换
await categoryRepository.find(id)
使用
await categoryRepository.findOne(id)
find
将返回Array
中的项目。