使用 Sequelize 从多个表中获取数据
Get data from multiple tables using Seqeulize
我有两个表,Post 和 Comments,我试图通过 userId 获取所有 posts,并使用以下代码获取每个 post 的相关评论。我通过错误 " comment is not associated to post".
得到了所有 posts 但 nodejs
Post Table
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
评论Table
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)
}
})
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();
我有两个表,Post 和 Comments,我试图通过 userId 获取所有 posts,并使用以下代码获取每个 post 的相关评论。我通过错误 " comment is not associated to post".
得到了所有 posts 但 nodejsPost Table
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
评论Table
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)
}
})
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();