【发布时间】:2021-12-19 09:10:13
【问题描述】:
我已将表配置为与其自身的多对多关系。这是一个实现“界面”的表格——“我可以有一个概览,可审查”
///HasReviewModel
static associate(models) {
// define association here
this.belongsToMany(models.HasReview, {
through: models.HasReviewHasReview,
as: 'child',
foreignKey: 'childId',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
this.belongsToMany(models.HasReview, {
through: models.HasReviewHasReview,
as: 'parent',
foreignKey: 'parentId',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
});
this.hasMany(models.Like, {onDelete: "cascade", onUpdate: "cascade", foreignKey: {allowNull: false}});
}
此外,在代码中,我调用 addChild() 将记录添加到链接表中,小说(帖子)将有评论(评论)。
async writeReview(novelId, userId, text) {
const novel = await db.Novel.findOne({
where: {id: novelId},
include: [{model: db.HasReview}]
});
let transaction;
try {
// get transaction
transaction = await db.sequelize.transaction();
const newReviewInterface = await db.HasReview.create({});
const review = await db.Review.create({
text: text,
hasReviewId: newReviewInterface.id,
userId: userId
});
//AddChild - novel added like child
novel.hasReview.addChild(newReviewInterface, {
through: {status: 'review'}
});
// AddParent - novel added like child too
// newReviewInterface.addParent(novel.hasReview, {
// through: {status: 'review'}
// });
if (!review)
throw new Error(`Не удалось создать комментарий, отмена транзакции`);
// commit
await transaction.commit();
return review;
但由于某种原因,它的工作方式相反。父母和孩子换地方。
数据库记录: https://i.stack.imgur.com/dI42m.png
如果我们调用 addParent 方法,它会再次反转并创建我需要的记录。 为什么?以及如何使其正常工作?我哪里做错了?
附:我面前的任务是制定一种通用的方式来评论任何实体。 无论是小说、帖子还是其他评论。
【问题讨论】:
标签: mysql node.js sequelize.js