Monday, 12 June 2017

sequelize error model is not associated to another model

I want to include a BelongsTo association

I have 2 models

user , team team has many users, but user belongs to one team only, and team has a team leader

here is user model definition

module.exports = (sequelize, DataTypes) => {
   const user = sequelize.define('user', {
    username: {
    type: DataTypes.STRING,
    allowNull: false
  },
    password: {
    type: DataTypes.STRING,
    allowNull: false
  },
    team_id: {
    type: DataTypes.INTEGER,
    allowNull: false
  }
},
{
  classMethods: {
   associate: (models) => {
     user.belongsTo(models.team,{
        targetkey: 'id',
        foreignKey: 'team_id'
     });
   },
 },
});
return user;
};

here is team model definition

module.exports = (sequelize, DataTypes) => {
  const team = sequelize.define('team', {
   name: {
   type: DataTypes.STRING,
   allowNull: false
  },
   leader: {
   type: DataTypes.INTEGER,
   allowNull: false
  }
{
  classMethods: {
    associate: (models) => {
     team.hasMany(models.user, {
       foreignKey: 'id'
     });
     team.belongsTo(models.user,{
       targetkey: 'id',
       foreignKey: 'leader'
     });
   },
  },
 });
  return team;
 };

I want to get team information for each user when list users something like this

{
  "id": 3,
  "username": "user123",
  "password": "password",
  "team_id": 1,
  "team": {
       "name": "name",
       "leader": "leader_name"
   }
}

I tried to include team but the the response was empty

here is the the code:

list(req, res){
        return models.user.findAll({
            include: [{
              model: models.team
            }],
            offset: req.query.offset,
            limit: req.query.limit

        })
        .then(function(users){

        res.status(200).send(users)
        })
        .catch(function(error){
        res.status(400).send(error)
        })
    }

Response was empty

the output was {} error was team is not associated to user

Dialect: postgres

Database version: 9.6.3

Sequelize version: 3.30.4

I don't use aliases, I wonder what might be wrong in my definition

Advance very grateful for the help



via luna

No comments:

Post a Comment