【发布时间】:2019-08-22 14:03:59
【问题描述】:
当我通过 Sequalize.js 将数据传递到我的数据库时,除了食物表中仍然为空的 FK“shops_ID”之外,所有内容都正确存储。
我读过其他类似的主题,但没有任何帮助。
我将不胜感激任何帮助/指导。
我正在使用带有以下 db-setup 的 mysql
Shops (mysql-table)
- id (pk)
- shopName
Food (mysql-table)
- id (pk)
- foodName
- shops_ID (fk connected to "id" in shops table)
shops.js
const Sequelize = require("sequelize");
const db = require("../database/db_shops.js"); //DB connection
const shops = db.sequelize.define(
"shops",
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
shopName: {
type: Sequelize.STRING
);
module.exports = shops;
food.js
"use strict";
const Sequelize = require("sequelize");
const db = require("../database/db_shops.js"); //DB connection
var shops = require("../models/shops");
const food = db.sequelize.define(
"food",
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
foodName: {
type: Sequelize.STRING
},
shops_ID: {
type: Sequelize.INTEGER,
references: {
model: "shops",
key: "id"
}
}
}
);
module.exports = food;
association.js
const food = require("./food");
const shops = require("./shops");
food.belongsTo(shops, { foreignKey: "shops_ID" });
module.exports = { food: food, shops: shops };
(编辑) 这就是我将数据发布到 mysql-db 的方式:
const express = require("express");
const router = express.Router();
const cors = require("cors");
const db = require("../models/association.js");
const Shops = db.shops;
const Foods = db.food;
router.use(cors());
router.post("/sell", (req, res, next) => {
var data = req.body.foodDefined;
var food = [];
for (var i = 0; i < data.length; i++) {
food.push({
foodName: data[i].foodName,
});
}
const shops = {
shopsName: req.body.shopsName,
};
if (!errors.isEmpty()) {
res.send(errors);
} else {
Shops.create(shops)
.then(Shops => {
Foods.bulkCreate(food);
res.json({ status: Shops.shopsName + " Registered!" });
})
.catch(err => {
res.send("error: " + err);
});
}
});
module.exports = router;
【问题讨论】:
-
向我们展示您如何存储数据
-
@rkm 我已经添加了上面的代码
标签: javascript mysql database foreign-keys sequelize.js