Home > Mobile >  How to setup hasOne and belongsTo relation in Postgres Sequelize
How to setup hasOne and belongsTo relation in Postgres Sequelize

Time:04-29

I have two tables one is User Table and another one is the Invitation table.

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
  }
  User.init({
    uuid:{
       type:DataTypes.UUID,
       defaultValue:DataTypes.UUIDV4,
       primaryKey:true
    },
    name: {
      type:DataTypes.STRING,
      allowNull:false
    },
    email: {
      type:DataTypes.STRING,
      allowNull:false
    },
   
    },
  }, {
    sequelize,
    tableName: 'users',
    modelName: 'User',
    timestamps: false,
    classMethods: {
      associate:function(models){
        User.hasOne(models.Invitation )
      }
    }
  });
  return User;
};

and

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Invitation extends Model {
  }
  Invitation.init({
    uuid:{
       type:DataTypes.UUID,
       defaultValue:DataTypes.UUIDV4
    },
    user_name: {
      type:DataTypes.STRING,
      allowNull:false
    },
    userTo: {
      type:DataTypes.STRING,
      //allowNull:false
    },
  }, {
    sequelize,
    tableName: 'invitations',
    modelName: 'Invitation',
    timestamps: false,
    classMethods: {
      associate:function(models){
        Invitation.belongsTo(models.User,{foreignKey:'userTo'})
      }
    }
  });
  return Invitation;
};

userTo in the Invitation table has the same value as the User.UUID table. I want to fetch all data with findAll command but it is showing errro I tried to run sequelize query but it showed SequelizeEagerLoadingError error I know the query in SQL but facing a problem with this.

SELECT User.name, Invitation.CustomerName
FROM User
INNER JOIN Invitation ON User.uuid = Invitation.userTo; 

CodePudding user response:

userTo: {
  type:DataTypes.STRING,
  //allowNull:false
},

If this is your foreign key in Invitation model, don't add that as field in Invitation model as you already added association for the table. So you can remove that from Invitation model.

Once update, see if there is any error

CodePudding user response:

Finally solved the error. I set the association at the top of the models

   class User extends Model {
   
    static associate(models) {
      // define association here
      User.hasOne(models.Invitation,{foreignKey:'userTo'})
    }
  }

---
Invitation table
----

class Invitation extends Model {
    static associate(models) {
      // define association here
      Invitation.belongsTo(models.User)
    }
  }

and change the datatype of userTo to DataTypes.UUID .beacause datatype of common attribute should be same .

  • Related