【问题标题】:Node.js mysql many to many relationshipNode.js mysql 多对多关系
【发布时间】:2020-10-28 20:56:53
【问题描述】:

我正在尝试在不使用 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});
    });
};

【问题讨论】:

    标签: mysql node.js many-to-many


    【解决方案1】:

    是否需要使用 Sequelize?

    简短回答:不。

    长答案:Sequelize 是一种 ORM,可帮助您简化不同的数据库操作并节省您的时间和精力。 这就是为什么推荐使用 ORM 的原因,这样您可以更专注于业务逻辑,而不用担心管理数据库操作。

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

    Here,您可以找到最流行的 ORM 列表。

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

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

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

    1. 插入产品
    2. 插入类别
    3. product_idcategory_id 插入到product_categories 中。

    【讨论】:

    • 感谢您的回答。也许您知道我还应该做什么,即我创建用户的 POST 请求也会在 product_categories 表中添加一个类别。我正在发送 json 请求 { "name": "telefons", "categories": { "category_id": 1 } }
    • 您必须进行并发调用(使用承诺)才能插入数据。这样当您插入 product_categories 时,您就有 product_id 和 category_id。
    猜你喜欢
    • 2014-12-11
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2012-07-16
    • 2018-09-09
    • 2020-04-04
    相关资源
    最近更新 更多