mysql - Node.js mysql 多对多关系
问题描述
我正在尝试在不使用 Sequelize 的情况下使用 node.js 和 mysql 制作具有多对多关系的产品和类别。还是我一定要使用它?
在连接到具有关系的数据库创建表时:
connection.connect((err) => {
if (err) {
return console.error("error: " + err.message);
} else {
console.log("Connected to the MySQL server.");
let createProducts = `CREATE TABLE IF NOT EXISTS products(
product_id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR (255) NOT NULL,
description VARCHAR (255),
price DECIMAL (19,2),
sku VARCHAR (255),
image VARCHAR (255),
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE now())`;
let createCategories = `CREATE TABLE IF NOT EXISTS categories(
category_id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR (255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW())`;
let createProductsCategories = `CREATE TABLE IF NOT EXISTS products_categories(
id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
product_id INT UNSIGNED NOT NULL,
category_id INT UNSIGNED NOT NULL,
FOREIGN KEY (product_id) REFERENCES products (product_id) ON DELETE CASCADE,
FOREIGN KEY (category_id) REFERENCES categories (category_id) ON DELETE CASCADE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW())`;
connection.query(createProducts, function (err, results, fields) {
if (err) {
console.log(err.message);
}
});
connection.query(createCategories, function (err, results, fields) {
if (err) {
console.log(err.message);
}
});
connection.query(createProductsCategories, function (err, results, fields) {
if (err) {
console.log(err.message);
}
});
}
});
我还应该在产品和类别模型/控制器中包含哪些它们之间的关系会起作用?在创建具有类别的产品时,数据会被插入到 products_categories 表中吗?
产品型号:
const Categories = require("category.model");
// constructor
const Product = function (product) {
this.name = product.name;
this.description = product.description;
this.price = product.price;
this.sku = product.sku;
this.image = product.image;
};
Product.create = (newProduct, result) => {
mysql.query("INSERT INTO products SET ?", newProduct, (err, res) => {
if (err) {
result(err, null);
return;
}
result(null, {id: res.insertId, ...newProduct});
});
};
产品控制器:
const Product = require("../models/product.model.js");
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
const product = new Product({
name: req.body.name,
description: req.body.description,
price: req.body.price
});
Product.create(product, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Error occurred while creating the new Product."
});
else res.send(data);
});
};
产品路线:
module.exports = app => {
const products = require("../controllers/product.controller.js");
app.post("/products", products.create);
类别型号:
const Category = function (category) {
this.name = category.name;
};
Category.create = (newCategory, result) => {
mysql.query(`INSERT INTO categories SET ?`, newCategory, (err, res) => {
if (err) {
result(err, null);
return;
}
result(null, {id: res.insertId, ...newCategory});
});
};
解决方案
是否需要使用 Sequelize?
简短的回答:没有。
长答案:Sequelize 是一个 ORM,它可以帮助您简化不同的数据库操作并节省您的时间和精力。这就是为什么建议使用 ORM 以便您可以更多地关注业务逻辑而不是担心管理 DB 操作的原因。
而且 Sequelize 并不是唯一可以实现这些目标的 ORM。
在这里,您可以找到最流行的 ORM 列表。
产品和类别之间的关系如何运作?
您的架构看起来不错。现在,如果您正确插入,它将完成工作。
插入时,请确保按照以下步骤操作。
- 插入产品
- 插入类别
- 获取
product_id
并将category_id
它们插入到 product_categories 中。
推荐阅读
- r - 完美对齐密度图和 geom_col 的 X 轴值
- node.js - 如何修复intellij找不到节点解释器,但节点文件在文件夹中
- xamarin - 自定义 Azure B2C 登录页面策略(注册登录) - 查找 API 元素列表以自定义 MSFT 登录容器内容
- hadoop - 优化 Hadoop 的记录写入
- api - 无法弄清楚 NHL 官方 API 的端点。
- javascript - 在 React 中,如何在通过 redux 更改 prop 时同步搜索框的 2 个输入状态
- node.js - 更新 lodash 版本到 4.17.4 破解代码
- ios - 以编程方式带图标的分段控制
- python - 使用 sqlparse 添加动态 sql 限制
- vhdl - 如果信号也在 VHDL 的敏感度列表中,我可以修改进程中的信号吗?