例如我有两个1:N的模型
const Product = db.define("product", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
}
});
const Category = db.define("category", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
}
});
Product.Category = Product.belongsTo(Category);
Category.Product = Category.hasMany(Product);
如果我想一起创建类别和产品,我会做:
await Category.create(
{
name: "test-category-2",
products: [{ name: "p1" }, { name: "p2" }]
},
{ include: [Product] }
);
如何创建具有现有关联的实例,例如我有产品,并且想要添加/更新带有新类别的category(categoryId)关系,就像这样:
const category = await Category.create(
{
name: "test-category-1",
products: [products[0].id, products[1].id] // add/update categoryId in this products
},
);
它必须创建新类别并更新现有产品的categoryId,但是在上面的代码中,它尝试像第一个示例一样创建产品