使用 Sequelize 创建新记录并更新关联表

时间:2021-06-24 16:15:26

标签: node.js sequelize.js

我有两个单独的表 Comments & CommentActivites,这些表是由 Sequelize 关联和创建的。我正在尝试为 CommentActivites 表中的每个赞创建一条记录,然后同时更新 Comments 表中的总赞。

每条评论都成功添加了新行,但是它不会更新评论表中的总评论。

我正在尝试的代码:

const router = require('express').Router()
const verify = require('../validation/verifyToken')
const Comments = require('../models/comments')
const CommentActivity = require('../models/commentActivity')


router.patch('/comments/update/likes', verify, async (req,res) => {
    const {
        id
        commentId
     } = req.body 

     //check if comment liked by the same user

    let likeExist = await CommentActivity.findOne(
        {where: 
            {userId: id, commentId: commentId}
        })
        
    if(likeExist) return res.status(400).send('Cannot Like Twice')

    // update find relevant comment
    let comment = await Comments.findOne({where: {id: commentId}})

    // current Total Likes
    currentTotalLikes = comment.totalCommentLikes

    const commentActivity = CommentActivity.create ({
            commentId : commentId,
            userId :  id,
            commentLikes : 1
        })
    
        try {
            const savedCommentLikes = await commentActivity
            const updatedComment = await Comments.update({ totalCommentLikes: currentTotalLikes + 1 });
            console.log(updatedComment)
            res.send(savedCommentLikes)
    }
    catch({errors}) {
        res.status(400).send(errors)
    }
})

评论表

const {Sequelize, DataTypes} = require('sequelize')
const db = require('../config/db')

const Comment = db.define('comment', {
    id:{
        type: DataTypes.INTEGER(255),
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    commentUUID:{
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4
    },
    commentText:{
        type: DataTypes.TEXT,
        allowNull: false
    },
    totalCommentLikes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    totalCommentStrikes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    totalCommentQuotes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    userId:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id'
        } 
    }, postId:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'post',
            key: 'id'
        } 
    }
},{
    freezeTableName: true
  })

  module.exports = Comment

评论活动表

const {Sequelize, DataTypes} = require('sequelize')
const db = require('../config/db')

const CommentActivity = db.define('commentActivity', {
    Id:{
        type: DataTypes.INTEGER(255),
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    commentAcitivtyUUID:{
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4
    },
    commentLikes: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    commentStrikes: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    commentQuotes: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    commentId:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'comment',
            key: 'id'
        } 
    },
    userId:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id'
        } 
    }
},{
    freezeTableName: true
  })

module.exports = CommentActivity

这就是我创建表格的方式

const db = require('../config/db')

const PostActivity = require('./postActivity')
const CommentActivity = require('./commentActivity')


User.hasMany(CommentActivity)
CommentActivity.belongsTo(User)
Comments.hasMany(CommentActivity)
CommentActivity.belongsTo(Comments)



db.sync({force: true})
.then((result) =>{
    console.log(result)
})
.catch((error) => {
    console.log(error)
})

0 个答案:

没有答案