Reputation: 313
I am trying to create three models with one to many relationships in Sequelize.
User, Post and Comment.
User - 1:M - Post Post - 1:M - Comment
When I Query All posts I want to include comments associated with the post as well. I am not able to achieve it. Below is the code. Can anyone extend help I am really confused with associations now.
User model
const User = sequelize.define('User', {
userId: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
allowNull:false
},
userName: {
type: DataTypes.STRING,
allowNull: false
},
userAuthId: {
type: DataTypes.STRING,
allowNull: false
},
userImage: {
type: DataTypes.STRING,
allowNull: false
},
role: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
}, {
freezeTableName: true
})
Post Model
const Post = sequelize.define('Post', {
postId: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
allowNull:false
},
title: {
type: DataTypes.STRING,
allowNull: false
},
postContent: {
type: DataTypes.TEXT,
allowNull: false
},
postImage: {
type: DataTypes.STRING,
allowNull: false
},
type: {
type: DataTypes.STRING,
allowNull: false
}
}, {
freezeTableName: true
})
Comments
const Comment = sequelize.define('Comments', {
commentId: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
primaryKey: true,
allowNull:false
},
comment: {
type: DataTypes.TEXT,
allowNull: false
}
}, {
freezeTableName: true
})
Associations
Post.belongsTo(User, {
as:'creator_id'
})
Post.belongsTo(User, {
as:'parent_for'
})
Post.hasMany(Comment, {
as: 'comments'
})
Comment.belongsTo(Post)
Comment.belongsTo(User, {
as: 'commentedUser',
foreignKey: 'userId'
})
Desired Result
{
"posts": [
{
"postId": "e1a7cc53-0376-43b6-b88b-9f51d95327b2",
"title": "New psoit",
"postContent": "e fed jefweef",
"postImage": "url",
"type": "regular",
"createdAt": "2021-07-07T07:40:24.095Z",
"updatedAt": "2021-07-07T07:40:24.095Z",
"creatorIdUserId": "14e72aac-8258-4533-a640-e41d78380084",
"parentForUserId": "08c781fa-ce27-43f5-aa16-de3e35218765",
"creator_id": {
"userId": "14e72aac-8258-4533-a640-e41d78380084",
"userImage": "url",
"userName": "[email protected]"
},
"comments": [
{
"commentId": "05d2c385-45d5-4259-9aef-803cc8750982",
"comment": "commt eds",
"createdAt": "2021-07-07T07:43:32.584Z",
"updatedAt": "2021-07-07T07:43:32.584Z",
"postId": "e1a7cc53-0376-43b6-b88b-9f51d95327b2",
"userId": "14e72aac-8258-4533-a640-e41d78380084"
}
]
}
]
}
Upvotes: 0
Views: 577
Reputation:
as I understood you want to have a join/relational database,
you can do as well as this, to have a many to many, use (hasMany)
#it means your post has many comments or likes and so on.
Post.hasMany(models.User, {
onDelete: "cascade",
});
this is your code and the above code is what I suggest to you!
Post.belongsTo(User, {
as:'creator_id'
})
Upvotes: 0