Sequelize Associate: User is not associated to Appointments

Viewed 167

Basically I have a user model and appointment model. The two models are linked with a one-to-many relationship. The Appointment table has two columns that are associated with the user model. When ever I try to include the properties of the user table in appointment, I get the above error.

These are my model designs

Appointment Model

export default ({
    sequelize
}:{
    sequelize: Sequelize
}) => {
    const Appointments: ModelDefined<AppointmentsAttribute, AppointmentsCreationAttributes>  = sequelize.define('Appointments', {
        appointmentId: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true,
        },
        client: {
            type: DataTypes.STRING,
            allowNull: false,
            references: {
                model: 'Users',
                key: 'uid'
            }
        },
        serviceProvider: {
            type: DataTypes.STRING,
            allowNull: false,
             references: {
                model: 'Users',
                key: 'uid'
            }
        },
        
    })

    return Appointments
}

User Model

export default ({
    sequelize
}: {
    sequelize: Sequelize
}) => {
    const User: ModelDefined<UserAttribute, UserCreationAttributes> = sequelize.define('User', {
        uid: {
            type: DataTypes.STRING,
            allowNull: false,
            unique:true,
            primaryKey: true
        },
        firstname: {
            type: DataTypes.STRING,
            allowNull: false,
        },
        lastname: {
            type: DataTypes.STRING,
            allowNull: false,
        },
       
    }
    })
    return User

}

I have associated the user and appointment models with

        Users.hasMany(Appointments);

The code that I am trying to use to fetch the appointment data and include the corresponding user value is

db.appointment.findAll({
                where: {
                    client: this.uid
                },

                include: 'Users'
            })
1 Answers

Sequelize always use associations for models whose association method was called. i.e. if you call Model1.hasMany(Model2) then you can execute queries like:

Model1.findAll({
  include: [{
   model: Model2
  }]
}

and NOT vice versa like this:

Model2.findAll({
  include: [{
   model: Model1
  }]
}

If you wish to request appointment with users as an associated model then you need to add a reversed association from Appointments to Users like this:

Users.hasMany(Appointments);
Appointments.belongsTo(Users);
Related