Friday 2 June 2017

get object in a 1 to many relationship

I have 2 models: User and Foto.

1 User can have a lot of fotos, and each foto is related to 1 specific user.

So at the moment i need to get all the fotos, and for each foto get the specific user too(id and username are enough).

I tried to solve this with eager loading with the includes, but it doesn't work it says that the tables are not associated, so in this case i just need to query the user table for the fotoId but how can i get that user object inside the Foto?

My User Model:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:false,
      defaultValue:2
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        associate: function(models){
          User.hasMany(models.Foto,{foreignKey: "userId", as: "Foto"});
        }

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });

  return User;
}

Foto object:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');


module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    lat: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lon: {
      type: DataTypes.STRING,
      allowNull: true
    },
    altitude: {
      type: DataTypes.STRING,
      allowNull: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    plantId: {
      type: DataTypes.INTEGER,
      allowNull: true
    },
  },
    {
      associate: function (models) {
        Foto.hasOne(models.User, {as:'User'});
      }
    }
  );


  return Foto;
}

my route:

allPictures: function (req, res) {
    Foto.findOne({where:{id: 1}})
    .then(function (foto) {
        res.send(foto);
        console.log(foto.getuser());
    })
},

getUser is not a function, is not working :/



via Filipe Costa

No comments:

Post a Comment