简体   繁体   中英

Sequelize how to join 2 tables 1:N

I have 2 models: User and Foto

Each User has a lot of fotos, and each foto can have just 1 user related.

To do that i use include , the problem is, i can use the include just when i am querying the user and not when i query the foto.

I get there is no relationshop between User and foto problem.

So at the moment i have this:

Model User:

"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: "Fotos"});
        }

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

    });

  return User;
}

Model Foto:

"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.belongsToMany(models.User, {as:'Users'});
      }
    }
  );


  return Foto;
}

then i try to get something like this in a json three:

[{
FotoA:{
prop1:value1,
prop2:value2,
user:{
userProp1
}
}
FotoB:{

}

}]

on my route i do the following:

allPictures: function (req, res) {
    Foto.findAll({include: [{ model: User, as: "Users",where:{userId: User.id} }]})
    .then(function (fotos) {
        res.send(fotos);
    })
},

if there is a better way to do this instad of eager loading please share it, i just need to get the userId and the username.

Thanks

I guess you defined the association wrong, as you mentioned a Foto should belong to one User.

try

Foto.belongsTo(model.User);

instead of

associate: function (models) {
  Foto.belongsToMany(models.User, {as:'Users'});
}

And also there should be no need for the where clause when selecting. If your associations are defined correctly, you can simply do

Foto.findAll({include: [models.User]})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM