【问题标题】:Sequelize how to join 2 tables 1:N续集如何加入2个表1:N
【发布时间】:2017-06-02 12:44:43
【问题描述】:

我有 2 个模型:用户和照片

每个用户有很多照片,每张照片只能有 1 个相关用户。

为此,我使用 include,但问题是,我只能在查询用户时使用 include,而不是在查询照片时使用。

我知道用户和照片问题之间没有关系。

所以目前我有这个:

模型用户:

"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;
}

模特照片:

"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;
}

然后我尝试在 json 三中得到类似的东西:

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

}

}]

在我的路线上,我执行以下操作:

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

如果有更好的方法来做这个而不是急切的加载,请分享它,我只需要获取 userId 和用户名。

谢谢

【问题讨论】:

    标签: javascript node.js postgresql sequelize.js


    【解决方案1】:

    我猜你定义了错误的关联,因为你提到了一个 Foto 应该属于 一个用户。

    试试

    Foto.belongsTo(model.User);
    

    而不是

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

    选择时也不需要where clause。如果你的关联定义正确,你可以简单地做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2011-01-29
      相关资源
      最近更新 更多