如何在Sequelize中使用belongsToMany?

时间:2017-07-08 04:24:47

标签: javascript node.js postgresql http sequelize.js

我正在创建一个使用sequelize连接到postgres数据库的Web应用程序。我已经设法自学了如何使用hasMany和belongsTo来调用,创建和销毁数据。我在使用belongsToMany时遇到了麻烦。

在我的服务器中,我正在尝试创建一个属于多个用户作为骑手的旅行,并为用户所属的旅行者添加了一个关联。我希望能够在POST请求上创建一个旅行,但无法弄清楚如何调用Ids。

///// MODELS trip.js

module.exports = function(sequelize, DataTypes) {
  var Trip = sequelize.define("Trip", {
    driverStart: DataTypes.STRING,
    driverEnd: DataTypes.STRING,
    riderStarts: DataTypes.ARRAY(DataTypes.STRING),
    riderEnds: DataTypes.ARRAY(DataTypes.STRING),
    tripDate: DataTypes.DATE,
    tripHour: DataTypes.INTEGER,
    availableSeats: DataTypes.INTEGER,
    price: DataTypes.INTEGER,
    tripIsActive: DataTypes.BOOLEAN
  });
  Trip.associate = function(models) {
    Trip.hasMany(models.User, {
      through: "riders_on_trip",
      as: "riders",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    Trip.belongsTo(models.User, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return Trip;
};

user.js的

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    profileImgUrl: DataTypes.STRING,
    fName: DataTypes.STRING,
    lName: DataTypes.STRING,
    yearOfBirth: DataTypes.INTEGER,
    gender: DataTypes.STRING,
    ratings: {
      type: DataTypes.ARRAY(DataTypes.INTEGER),
      defaultValue: [5]
    },
    onTrip: {
      type: DataTypes.BOOLEAN,
      defaultValue: false
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: sequelize.literal('NOW()')
    }
  });
  User.associate = function(models) {
    User.hasMany(models.RideRequest, {
      onDelete: "CASCADE",
      foreignKey: "riderId"
    });
    User.hasMany(models.DriveRequest, {
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
    User.hasMany(models.Notification, {
      as: 'sender',
      onDelete: "CASCADE",
      foreignKey: "senderId"
    });
    User.hasMany(models.Notification, {
      as: 'receiver',
      onDelete: "CASCADE",
      foreignKey: "receiverId"
    });
    User.belongsToMany(models.Trip, {
      as: "riders",
      through: "riders_on_trip",
      onDelete: "CASCADE",
      foreignKey: "riderIds"
    });
    User.hasMany(models.Trip, {
      as: "driver",
      onDelete: "CASCADE",
      foreignKey: "driverId"
    });
  };
  return User;
};

/////控制器

trip.js

  create: function create(req,res) {
    // var decodedIds = req.params.riderIds.split("-");
    var decoded = jwt.decode(req.query.token);
    // console.log(decodedIds + '------------------ DECODED IDS ----------------');
    model.User.set
    return model.Trip.create({
      driverStart: req.body.driverStart,
      driverEnd: req.body.driverEnd,
      riderStarts: req.body.riderStarts,
      riderEnds: req.body.riderEnds,
      tripDate: req.body.tripDate,
      tripHour: req.body.tripHour,
      availableSeats: req.body.availableSeats,
      price: req.body.price,
      tripIsActive: req.body.tripIsActive,
      driverId: req.params.driverId,
      riders: [{riderIds: 2}, {riderIds: 2}, {riderIds: 3}]
    }).then(function (trip) {
      console.log(trip.riderIds + '------------ RIDER IDS ---------------');
      return res.status(201).json({
        message: 'Trip created successfully',
        obj: trip
      });
    }).catch(function (err) {
      return res.status(400).json({
        title: 'Error occured while creating trip',
        error: err
      });
    });
  },

是否有任何编程大师可以给我一个简短的解释,说明如何在续集中创建这种关联的旅行?

1 个答案:

答案 0 :(得分:0)

如果要设置多对多表,则不需要Trip和User上的hasMany,belongsTo内容。看起来你正确设置了多对多的表,但如果你需要查询属于特定用户的行程,你需要添加另一个关联

Trip.belongsToMany(models.User, {
  as: "driver",
  through: "riders_on_trip",
});

你得到了要点。

你可以像这样得到骑手ids:

trip.getRiders().then(function (rider){
    return riders.map((rider) => {
        return rider.id;
    });
)};