Я новичок в реляционной базе данных. Я использую node js и express для бэкэнда, REST API и база данных Postgresql. Я использую Sequelize для подключения и моделей. Я создал две модели: одна - студент, а другая - курс. Моя цель - один студент может иметь несколько курсов и не допустить дублирования имени, телефона, электронной почты студента. Я успешно подключаюсь к базе данных и могу публиковать, получать, обновлять, удалять как студента, так и модель курса. Из тестирования приложения я использую Почтальон. Но я не уверен, правильно ли я отношусь к отношениям между студентом и курсом. А также я не знаю, как отобразить отношения между двумя таблицами. Я буду очень рад, если кто-нибудь поможет мне.
Я хочу показать мои вот так:
{
"students": [
{
"id": 1,
"name": "Anni Anonen",
"birthday": "1992-02-28",
"address": "Kivakatu 1",
"zipcode": "00500",
"city": "Helsinki",
"phone": "+358506760702",
"email": "anni.anonen@testing.fi",
"courses": [1,2,3] //SHOW COURSES LIKE THIS
},
{
"id": 2,
"name": "Ville Anonen",
"birthday": "2000-03-28",
"address": "Hämeentie 1",
"zipcode": "00510",
"city": "Helsinki",
"phone": "+358508660702",
"email": "ville.anonen@testing.fi",
"courses": [3]
},
{
"id": 3,
"name": "Tapani Kumpu",
"birthday": "1999-05-28",
"address": "Jokukatu 17",
"zipcode": "00560",
"city": "Helsinki",
"phone": "+358502330702",
"email": "tapani.kumpu@testing.fi",
"courses": [1,4]
}
],
"courses": [
{
"id": 1,
"name": "Gymnastics 1",
"startdate": "2020-01-01",
"enddate": "2020-02-10"
},
{
"id": 2,
"name": "Gymnastics 2",
"startdate": "2020-01-01",
"enddate": "2020-02-10"
},
{
"id": 3,
"name": "Fitness 1",
"startdate": "2020-02-01",
"enddate": "2020-02-20"
},
{
"id": 4,
"name": "Dance 1",
"startdate": "2020-05-01",
"enddate": "2020-05-02"
}
]
}
Это мои модели
const sequelize = require("sequelize");
var con = new sequelize("school", "postgres", "password", {
host: "localhost",
dialect: "postgres",
pool: {
max: 5,
min: 0,
idle: 10000
}
});
const Student = con.define("student", {
name: {
type: sequelize.STRING,
allowNull: false
},
birthday: {
type: sequelize.DATEONLY,
allowNull: false
},
address: {
type: sequelize.STRING,
allowNull: false
},
zipcode: {
type: sequelize.INTEGER,
allowNull: false
},
city: {
type: sequelize.STRING,
allowNull: false
},
phone: {
type: sequelize.BIGINT,
allowNull: false
},
email: {
type: sequelize.STRING,
allowNull: false,
validate: {
isEmail: true
}
}
});
const Course = con.define("course", {
id: {
type: sequelize.INTEGER,
primaryKey: true
},
name: { type: sequelize.STRING },
startdate: { type: sequelize.DATEONLY },
enddate: { type: sequelize.DATEONLY },
studentId: { type: sequelize.INTEGER, foreignKey: true }
});
Student.hasMany(Course);
Course.belongsTo(Student);
//con.sync({ force: true });
module.exports = { Student, Course };
Это express сервер
require("dotenv").config();
const express = require("express");
const app = express();
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const { Student, Course } = require("./db");
//app middlewear
app.use(morgan("common"));
app.use(helmet());
app.use(cors());
app.use(express.json()); //body Parser
//student
app.get("/students", async (req, res, next) => {
try {
await Student.findAll().then(docs => {
const response = {
count: docs.length,
students: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
app.get("/students/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.put("/students/:id", async (req, res) => {
const id = req.params.id;
const update = req.body;
try {
await Student.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.delete("/students/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.post("/students", async (req, res, next) => {
try {
const logs = new Student(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
//course
app.get("/courses", async (req, res, next) => {
try {
await Course.findAll().then(docs => {
const response = {
count: docs.length,
courses: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
app.get("/courses/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.put("/courses/:id", async (req, res, next) => {
const id = req.params.id;
const update = req.body;
try {
await Course.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.delete("/courses/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
app.post("/courses", async (req, res, next) => {
try {
const logs = new Course(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`? App is listening at port ${port}!`));