【发布时间】:2021-11-20 21:34:30
【问题描述】:
您好,谁能帮我创建可以插入数组数据类型的续集模型。我的情况是我有 2 个模型(product 和 order),我想要做的是在订单模型中我有 order_item,它将是 product_id 的数组并引用 product 表,这样我就可以获得所需的其余属性。
**注意:我计划使用原始查询
这是我的代码:
模型产品
const { DataTypes } = require("sequelize");
const sequelize = require("../config");
const Product = sequelize.define(
"products",
{
id: {
primaryKey: true,
type: DataTypes.UUID,
allowNull: false,
},
p_image: {
type: DataTypes.TEXT,
allowNull: false,
},
p_name: {
type: DataTypes.STRING,
allowNull: false,
},
p_desc: {
type: DataTypes.TEXT,
allowNull: false,
},
p_prize: {
type: DataTypes.INTEGER,
allowNull: false,
},
p_size: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
freezeTable: true,
}
);
module.exports = Product;
模型顺序
const { DataTypes, Deferrable } = require("sequelize");
const sequelize = require("../config");
const Product = require("./model_product");
const Order = sequelize.define("orders", {
id: {
primaryKey: true,
type: DataTypes.UUID,
allowNull: false,
},
o_items: {
type: DataTypes.ARRAY(DataTypes.UUID),
allowNull: false,
references: {
model: Product,
key: "id",
deferrable: Deferrable.INITIALLY_IMMEDIATE,
},
},
o_quantity: {
type: DataTypes.INTEGER,
allowNull: false,
},
o_total_price: {
type: DataTypes.INTEGER,
allowNull: false,
},
});
module.exports = Order;
我打算进行如下插入查询:
const sql = `INSERT INTO orders (id, o_items, o_quantity, o_total_price, "createdAt", "updatedAt")
VALUES (?, ?, ?, ?, now(), now())
ON CONFLICT (id) DO NOTHING
RETURNING *;`;
当我启动服务器npm start 时,我收到了cannot be implemented:
CREATE TABLE IF NOT EXISTS "orders" ("id" UUID NOT NULL , "o_items" UUID[] NOT NULL REFERENCES "products" ("id") DEFERRABLE INITIALLY IMMEDIATE, "o_quantity" INTEGER NOT NULL, "o_total_price" INTEGER NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
foreign key constraint "orders_o_items_fkey" cannot be implemented
编辑
我检查并似乎不可能存储外键数组,所以我将我的模型更改为m:n product 和 order 到 order_items 之间的关系,如下所示:
但我的问题仍然是如何插入产品数组,例如:用户在一个订单中可以订购 3 种不同的产品。对不起,如果这个问题很愚蠢,但我是新手,任何人都请帮助解决这个问题,我也想通过查询来做,因为这是项目的要求。谢谢。
【问题讨论】:
标签: node.js postgresql express orm sequelize.js