javascript - Sequelize 如何连接 2 个表 1 :N

标签 javascript node.js postgresql sequelize.js

我有 2 个模型:User 和 Foto

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

为此,我使用 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);
    })
},

如果有更好的方法来实现这一点,请分享它,我只需要获取用户 ID 和用户名。

谢谢

最佳答案

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

尝试

Foto.belongsTo(model.User);

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

而且在选择时应该不需要 where clause。如果你的关联定义正确,你可以简单地做
Foto.findAll({include: [models.User]})

关于javascript - Sequelize 如何连接 2 个表 1 :N,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44329315/

相关文章:

javascript - 在 javascript 中交换数组元素时出现问题

javascript - 如何不断用新数据刷新图表?

javascript - 使用 Sinon 的假计时器时未触发 setTimeout

node.js - 带有 docker-compose : Container ID 166535 cannot be mapped to a host ID 的 Bitbucket 管道

json - 如何在 postgresql 9.3 中循环遍历 JSON 数组

javascript - 测试元素标签名称

javascript - 如何在时间和值(value)交换的 Highcharts 中绘制数据?

javascript - 未找到 Browserify 命令

postgresql - 在postgres中查找系列的长度

ruby-on-rails - Postgres 索引对原始 SQL 和 ActiveRecord 查询的影响截然不同