我正在使用Node构建测验应用。我在postgres中有两个模型," Quizes"和#34;问题。" Quizes有很多问题。我想用他们的问题查询所有的问题。我收到一个奇怪的错误:
Unhandled rejection SequelizeDatabaseError: column questions.questions_id does not exist
我不知道为什么要查找名为questions_id的列。那不在我的模特中。以下是两种型号:
测验模型:
const Sequelize = require('sequelize');
const {sequelize} = require('../db/sequelize');
const Quiz = sequelize.define('Quiz',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
title: {
type: Sequelize.STRING,
allowNull: false
}
},
{
tableName: 'quizes',
timestamps: false,
underscored: true
}
);
Quiz.associate = function(models) {
Quiz.hasMany(
models.Question,
{
as: 'questions',
foreignKey: { allowNull: false },
onDelete: 'CASCADE'
}
)
}
module.exports = {
Quiz
}
问题模型:
'use strict';
const Sequelize = require('sequelize');
const {sequelize} = require('../db/sequelize');
const Question = sequelize.define('Quiz',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
question: {
type: Sequelize.STRING,
allowNull: false
},
answer_one: {
type: Sequelize.STRING,
allowNull: true
},
answer_two: {
type: Sequelize.STRING,
allowNull: true
},
answer_three: {
type: Sequelize.STRING,
allowNull: true
},
answer_four: {
type: Sequelize.STRING,
allowNull: true
},
correct_answer: {
type: Sequelize.STRING,
allowNull: false
}
}, {
tableName: 'questions',
timestamps: false,
underscored: true
});
Question.associate = function(models) {
Question.belongsTo(
models.Quiz,
{
as: 'questions',
foreignKey: { allowNull: false },
onDelete: 'CASCADE'
}
);
}
module.exports = {
Question
}
抛出错误的路线:
app.get('/', (req, res) => Quiz.findAll(
{
limit: 50,
include: [{
model: Question,
as: 'questions'
}]
})
.then(quizes => res.json({
quizes
}))
);
我的SQL迁移:
BEGIN;
CREATE TABLE quizes (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL
);
CREATE TABLE questions (
id SERIAL PRIMARY KEY,
question TEXT NOT NULL,
answer_one TEXT,
answer_two TEXT,
answer_three TEXT,
answer_four TEXT,
correct_answer TEXT NOT NULL,
quiz_id INTEGER REFERENCES quizes ON DELETE CASCADE NOT NULL
);
INSERT INTO quizes (title) VALUES ('Mercury');
INSERT INTO quizes (title) VALUES ('Venus');
INSERT INTO quizes (title) VALUES ('Earth');
INSERT INTO quizes (title) VALUES ('Mars');
INSERT INTO quizes (title) VALUES ('Jupiter');
INSERT INTO quizes (title) VALUES ('Saturn');
INSERT INTO quizes (title) VALUES ('Uranus');
INSERT INTO quizes (title) VALUES ('Neptune');
INSERT INTO questions (question, answer_one, answer_two, answer_three, answer_four, correct_answer, quiz_id) VALUES ('What is Venues', 'A moon', 'A star', 'A planet', 'An asteroid', 'A planet', 1);
COMMIT;
答案 0 :(得分:0)
你的联系应该是这样的:
Quiz.hasMany(
models.Question,
{
as: 'questions',
foreignKey: 'quiz_id', // You need to define the foreign key
onDelete: 'CASCADE'
}
)
Question.belongsTo(
models.Quiz,
{
as: 'questions',
foreignKey: 'quiz_id', // You need to define the foreign key
onDelete: 'CASCADE'
}
);