javascript - Sequelize 不创建 set/get/add 方法
问题描述
我不确定我是否遗漏了什么,但 Sequelize 似乎没有创建从 belongsToMany(...) 关联派生的方法(在这种情况下:setRequest, getRequest, addRequest Sequelize Docs)
我正在尝试创建 N:N 关系(与食物和请求)。所以,arequest
可以有很多foods
,afood
可以有很多requests
我得到的错误:
(节点:4504)UnhandledPromiseRejectionWarning:TypeError:food.addRequests 不是函数
楷模
请求型号:
const { Model, DataTypes } = require('sequelize');
class Request extends Model {
static init(sequelize) {
super.init({
//Format
client: DataTypes.STRING(70),
time_processing: DataTypes.INTEGER,
time_cooking: DataTypes.INTEGER,
time_paying: DataTypes.INTEGER,
//Has one Table
}, {
//Conection
sequelize
})
}
static associate(models) {
this.belongsTo(models.Table, { foreignKey: 'fk_table', as: 'table', targetKey: 'id' });
this.belongsTo(models.Employee, { foreignKey: 'fk_employee', as: '' });
this.belongsToMany(models.Food, { foreignKey: 'fk_request', through: 'requests_foods', as: 'request' });
}
}
module.exports = Request;
食品型号:
const { Model, DataTypes } = require('sequelize');
class Food extends Model {
static init(sequelize) {
super.init({
//Format
name: DataTypes.STRING(40),
image: DataTypes.STRING,
price: DataTypes.FLOAT,
storage: DataTypes.INTEGER,
//Is used By Many Requests
}, {
//Conection
sequelize,
tableName: 'foods'
})
}
static associate(models) {
//Through: Table used to join data
//foreignKey: Which column of requests_foods is used to reference to models.Request
this.belongsToMany(models.Request, { foreignKey: 'fk_food', through: 'requests_foods', as: 'foods' });
this.belongsTo(models.Category, { foreignKey: 'fk_category', as: 'category' });
}
}
module.exports = Food;
数据透视表:
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('requests_foods', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
fk_request: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'requests', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'CASCADE',
},
fk_food: {
type: Sequelize.INTEGER,
allowNull: false,
references: { model: 'foods', key: 'id' },
onUpdate: 'CASCADE',
onDelete: 'RESTRICT'
},
amount: {
type: Sequelize.INTEGER,
allowNull: false,
},
created_at: {
type: Sequelize.DATE,
allowNull: false,
},
updated_at: {
type: Sequelize.DATE,
allowNull: false,
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('requests_foods');
}
};
最后是控制器(抛出错误的地方)
const Request = require('../models/Request');
const Food = require('../models/Food');
module.exports = {
async list(req, res) {
const dbResponse = await Request.findAll();
return res.json(dbResponse);
},
async add(req, res) {
const { client, time_processing, time_cooking, time_paying, fk_table, fk_employee, foods } = req.body;
console.log(req.body);
const dbResponse = await Request.create({ client, time_processing, time_cooking, time_paying, fk_table, fk_employee });
//Look for food list
foods.map(async item => {
console.log('ITEM:', item);
const food = await Food.findByPk(item.fk_food)
console.log(food);
food.addRequests(); //ERROR HERE
})
return res.json(dbResponse);
}
}
笔记:
请求已添加,但requests_foods未添加。
我尝试更改为:addRequest()、setRequests、setRequest(),但没有任何效果,我 console.log 对象,似乎该对象没有任何方法:
{ client: 'Wesley Almeida Braga',
time_processing: 0,
time_cooking: 0,
time_paying: 0,
fk_table: 1,
fk_employee: 1,
foods: [ { fk_food: 1 } ] }
Executing (default): INSERT INTO `requests` (`id`,`client`,`time_processing`,`time_cooking`,`time_paying`,`created_at`,`updated_at`,`fk_employee`,`fk_table`) VALUES (DEFAULT,?,?,?,?,?,?,?,?);
ITEM: { fk_food: 1 }
Executing (default): SELECT `id`, `name`, `image`, `price`, `storage`, `created_at` AS `createdAt`, `updated_at` AS `updatedAt`, `fk_category` FROM `foods` AS `Food` WHERE `Food`.`id` = 1;
Food {
dataValues:
{ id: 1,
name: 'Carne de Sol',
image: 'example_2.png',
price: 25,
storage: 10,
createdAt: 2020-01-12T03:48:34.000Z,
updatedAt: 2020-01-12T03:48:34.000Z,
fk_category: 1 },
_previousDataValues:
{ id: 1,
name: 'Carne de Sol',
image: 'example_2.png',
price: 25,
storage: 10,
createdAt: 2020-01-12T03:48:34.000Z,
updatedAt: 2020-01-12T03:48:34.000Z,
fk_category: 1 },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: false,
underscored: true,
paranoid: false,
rejectOnEmpty: false,
whereCollection: { id: 1 },
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: {},
indexes: [],
name: { plural: 'Food', singular: 'Food' },
omitNull: false,
sequelize:
Sequelize {
options: [Object],
config: [Object],
dialect: [MysqlDialect],
queryInterface: [QueryInterface],
models: [Object],
modelManager: [ModelManager],
connectionManager: [ConnectionManager],
importCache: {} },
tableName: 'foods',
hooks: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes:
[ 'id',
'name',
'image',
'price',
'storage',
'createdAt',
'updatedAt',
'fk_category' ] },
isNewRecord: false }
解决方案
推荐阅读
- html - 如何设置 HTML 分页样式
- arrays - Mongodb - 在嵌套数组中只取一个元素
- android - 渲染期间引发的异常:16(详细信息)
- apache - 如何在 Apache 中为一个 RewriteCond 使用 Multile RewriteRules?
- eigen - 如何对向量的特定索引使用 cwise 操作?(本征)
- php - 使用 PHP 在 MySQL 中破坏 UTF8 字符
- c - 使用浮点二进制“0b”的算术运算
- java - 从函数类显示 JOption 窗格
- websphere - 业务连续性 Active\Active Websphere MQ 集群
- ios - 将应用程序提交到 App Store 之前的验证错误消息