я новичок, мне нужна помощь в работе с nodejs

#mysql #node.js

#mysql #node.js

Вопрос:

у меня есть три таблицы (вопросы , варианты , ответы) в этих трех таблицах родительская модель-это вопросы, а затем дочерние-это варианты и ответы, поэтому я хочу удалить дочерние данные, также вызываемые по идентификатору родителя

Вот вопросы моделей

 import Sequelize from "sequelize"; import Exam from "../../models/exam.js";  import sequelize from "../../utilities/database.js";  const Question = sequelize.define("question", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: true,  },   questiontext: {  type: Sequelize.STRING,  allowNull: true,  },  questiontexthindi: {  type: Sequelize.STRING,  allowNull: true,  },   questionImgURL: {  type: Sequelize.STRING,  allowNull: true,  },   description: {  type: Sequelize.TEXT,  allowNull: true,  },   examId: {  type: Sequelize.INTEGER,  allowNull: false,  references: {  model: Exam,  key: "id",  },  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Question;   

модели опций

 import Sequelize from "sequelize";  import sequelize from "../../utilities/database.js"; import Question from "./question.js";  const Option = sequelize.define("option", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: true,  },   optiontext: {  type: Sequelize.STRING,  // (Sequelize.STRING),  allowNull: false,  isLength: [2, 6],  },   questionId: {  type: Sequelize.INTEGER,  allowNull: false,  references: {  model: Question,  key: "id",  onDelete: "CASCADE",  },  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Option;   

Here is answers models

 import Sequelize from "sequelize";  import sequelize from "../../utilities/database.js"; import Question from "./question.js"; import Option from "./option.js";  const Answer = sequelize.define("answer", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: true,  },  questionId: {  type: Sequelize.INTEGER,  allowNull: false,  references: {  model: Question,  key: "id",  onDelete: "CASCADE",  },  },   optionId: {  type: Sequelize.INTEGER,  allowNull: true,  references: {  model: Option,  key: "id",  },  },   correctanswer: {  type: Sequelize.STRING,  allowNull: false,  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Answer;   

Here is my controller

 //models import Question from "../../../models/model-tesportal/option.js";  //helpers import { validationErrorHandler } from "../../../helpers/validation-error-handler.js";  export const deleteTestSeries = async (req, res, next) =gt; {  validationErrorHandler(req, next);  const questionId = req.params.questionId;  try {  const result = await Question.destroy({  where: {  questionId: questionId,  },  });  if (result[0] === 0) {  const error = new Error("Question not found");  error.statusCode = 404;  return next(error);  }  res.status(201).json({  message: "Question Deleted successfully",  });  } catch (err) {  if (!err.statusCode) {  err.statusCode = 500;  }  next(err);  } };   

i want to pass questionId in params and then delete data of that particular questionId will be deleted from parent and child tables

Ответ №1:

I got the solution from #geeks for geeks

i have to modify in my models where i wanna access those reference key Id just look at my models now it works perfectly :

here is questions model {parent}

 import Sequelize from "sequelize"; import Exam from "../../models/exam.js";  import sequelize from "../../utilities/database.js";  const Question = sequelize.define("question", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: "id", **lt;----- modify here**    },   questiontext: {  type: Sequelize.STRING,  allowNull: true,  },  questiontexthindi: {  type: Sequelize.STRING,  allowNull: true,  },   questionImgURL: {  type: Sequelize.STRING,  allowNull: true,  },   description: {  type: Sequelize.TEXT,  allowNull: true,  },   examId: {  type: Sequelize.INTEGER,  allowNull: false,  references: {  model: Exam,  key: "id",  },  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Question;   

модель дочерних опций

 import Sequelize from "sequelize"; import sequelize from "../../utilities/database.js"; import Question from "./question.js";  const Option = sequelize.define("option", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: true,  },   optiontext: {  type: Sequelize.STRING,  // (Sequelize.STRING),  allowNull: false,  isLength: [2, 6],  },   questionId: {  type: Sequelize.INTEGER,  allowNull: false,  onDelete: "CASCADE", **lt;----- modify here**  references: {  model: Question,  key: "id",  FOREIGNKEY: "id", **lt;----- modify here**  },  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Option;   

модели ответов для детей

 import Sequelize from "sequelize";  import sequelize from "../../utilities/database.js"; import Question from "./question.js"; import Option from "./option.js";  const Answer = sequelize.define("answer", {  id: {  type: Sequelize.INTEGER,  autoIncrement: true,  allowNull: false,  primaryKey: true,  },  questionId: {  type: Sequelize.INTEGER,  allowNull: false,  onDelete: "CASCADE", **lt;----- modify here**  references: {  model: Question,  key: "id",  FOREIGNKEY: "id", **lt;----- modify here**  },  },   optionId: {  type: Sequelize.INTEGER,  allowNull: true,  references: {  model: Option,  key: "id",  },  },   correctanswer: {  type: Sequelize.STRING,  allowNull: false,  },   isActive: {  type: Sequelize.BOOLEAN,  defaultValue: true,  }, }); export default Answer;   

контроллер основного кода

 //models import Question from "../../../models/model-tesportal/question.js"; //helpers import { validationErrorHandler } from "../../../helpers/validation-error-handler.js";  export const deleteTestSeries = async (req, res, next) =gt; {  validationErrorHandler(req, next);  try {  const result = await Question.destroy({  where: {  id: req.params.questionId,  },  });   if (result[0] === 0) {  const error = new Error("Question not found");  error.statusCode = 404;  return next(error);  }  res.status(201).json({  message: "Hey Admin Question Deleted successfully",  });  } catch (err) {  if (!err.statusCode) {  err.statusCode = 500;  }  next(err);  } };