首页 > 解决方案 > 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});
    });
};

标签: mysqlnode.jsmany-to-many

解决方案


是否需要使用 Sequelize?

简短的回答:没有。

长答案:Sequelize 是一个 ORM,它可以帮助您简化不同的数据库操作并节省您的时间和精力。这就是为什么建议使用 ORM 以便您可以更多地关注业务逻辑而不是担心管理 DB 操作的原因。

而且 Sequelize 并不是唯一可以实现这些目标的 ORM。

在这里,您可以找到最流行的 ORM 列表。

产品和类别之间的关系如何运作?

您的架构看起来不错。现在,如果您正确插入,它将完成工作。

插入时,请确保按照以下步骤操作。

  1. 插入产品
  2. 插入类别
  3. 获取product_id并将category_id它们插入到 product_categories 中。

推荐阅读