【问题标题】:Get data from multiple tables using Seqeulize使用 Sequelize 从多个表中获取数据
【发布时间】:2021-06-26 06:11:06
【问题描述】:

我有两个表,Post 和 Comments,我正在尝试按 userId 获取所有帖子,并使用以下代码获取每个帖子的相关 cmets。我通过错误“评论未与帖子相关联”获取所有帖子,但nodejs。

发布表

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

const Post = db.define('post', {
    id:{
        type: DataTypes.INTEGER(255),
        autoIncrement: true,
        allowNull: false,
        primaryKey: true
    },
    postId:{
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4
    },
    postText:{
        type: DataTypes.TEXT,
        allowNull: false
    },
    totalPostLikes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    totalPostStrikes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    totalPostQuotes: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    totalPostShare: {
        type: DataTypes.INTEGER,
        allowNull: true,
        defaultValue: 0
    },
    userId:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id'
        } 
    }
},{
    freezeTableName: true
  })

module.exports = Post

评论表

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 db = require('../config/db')

const User = require('./user')
const Post = require('./posts')
const Comments = require('./comments')


User.hasMany(Post)
Post.belongsTo(User)


Post.hasMany(Comments)
Comments.belongsTo(Post)
User.hasMany(Comments)
Comments.belongsTo(User)



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

获取数据的代码

router.get('/:id', authenticate, async (req,res) => {

    const { id } = req.params


    const data = await Post.findAll(
        {where: {userId: id},
        attributes: [
            'postText', 
            'totalPostLikes', 
            'totalPostStrikes',
            'totalPostQuotes',
            'totalPostShare'
        ],
         include:[{model: Comments, attributes:['commentText']}]   
    })


    try{
        res.send(data);

    } catch({errors}) {
        res.status(400).send(errors)
    }
})

【问题讨论】:

  • 问题解决了吗?

标签: node.js sequelize.js


【解决方案1】:
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const db = require('../models');

var main = async () => {
    try {
        const data = await db.post.findAll({
            where: { userId: 1 },
            attributes: ['postText', 'totalPostLikes', 'totalPostStrikes', 'totalPostQuotes', 'totalPostShare'],
            include: [{ model: db.comment, attributes: ['commentText'], as: 'comments' }],
        });
        console.log(JSON.parse(JSON.stringify(data)));
    } catch (e) {
        console.log(e);
    }
};
main();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2016-06-18
    • 2016-11-23
    相关资源
    最近更新 更多