TechSolutionsHere.com

Next.js and Sequelize with Associations

Coding sequelize

Next.Js With Sequelize Part 1

Today we will see how to create an associations in Sequelize.

In system analysis, a one-to-many relationship refers to the relationship between two entities X an Y in which element of X may be linked to many elements of Y, but a member of Y is linked to only one element of X.

For example, assume that you want to design a Blog data model, you can think about one User has many Posts, but one Post belongs to one User.

So the relationship between User entity and Post entity is one-to-many. That’s what we are going to do in this post.

And you can say this association is one to many relationship. Like the previous post, you should create another model which name is Post and it is like below

const postModel = (sequelize, Sequelize) => {
    const Post = sequelize.define('post', {
        id: {
            type: Sequelize.UUID,
            defaultValue: Sequelize.UUIDV4,
            primaryKey: true
        },
        title: {
            type: Sequelize.STRING,
            allowNull: false
        },
        body: {
            type: Sequelize.TEXT,
            allowNull: false
        },
    })

    return Post
}

export default postModel

And now into the index.js make the association like below

// models/index.js
import Sequelize from 'sequelize'
import userModel from './user.model'
// New added
import postModel from './Post'

// For full configuration you can see previous post
// And it is very important

db.Sequelize = Sequelize
// New added
db.sequelize = sequelize

db.users = userModel(sequelize, Sequelize)
// New added
db.posts = postModel(sequelize, Sequelize)

// New added
// Relationship Part
db.users.hasMany(db.posts, { as: 'posts' })
db.posts.belongsTo(db.users, {
    foreignKey: 'userId',
    as: 'user'
})

export default db

And that’s it 🙂

Exit mobile version