我想建立一个恋爱关系

时间:2018-10-07 13:11:49

标签: javascript sequelize.js

我正在使用同时具有联系人和消息的SMS应用程序。我创建了包含联系人和SMS表的表,其中包括ContactSms的关系表。联系人属于ToMany短信和SMS属于ManyToMany联系人。

我想让接收方电话和发送方电话将消息保存在sms表中,以将sender_id和Receiver_id添加到ContactSms表中

sms表:

const Sms = sequelize.define('Sms', {
    message: DataTypes.STRING,
    status: DataTypes.BOOLEAN
  }, {});
  Sms.associate = function(models) {
    // associations can be defined here
    Sms.belongsToMany(models.Contact, {
      through: 'ContactSms',
      as: 'contacts',
      foreignKey: 'sms_id'
    });
  };
  return Sms;
};

联系表:

const Contact = sequelize.define('Contact', {
    contact_name: DataTypes.STRING,
    contact_phone: {
      allowNull: false,
      type:DataTypes.STRING,
      validate: {
        not: ['[a-z]', 'i']
      }
    }
  }, {});
  Contact.associate = function(models) {
    // associations can be defined here
    Contact.belongsToMany(models.Sms, {
      through: 'ContactSms',
      as: 'sms',
      foreignKey: 'contact_id'
    });
  };
  return Contact;
};

下面的代码是我要保存与短信有关的两个联系人的工作。它正在保存消息,但没有将ID保存到ContactSms表中。我不知道我在做什么错。我需要帮助

sendSms(req, res) {
    return Contact
    .findAll( {
        where: {
          contact_phone: req.body.sender
        }
      } 
    )
    .then(sender => {
      let users = [sender]
       return Contact
         .findAll({
           where: {
             contact_phone: req.body.reciever
           } 
         }).then(reciever => {
           users.push(reciever)
           return users
         })
    }).then (users => {
      if (!users) {
        return res.status(404).send({
          message: 'Users Not Found',
        });
      }
      return Sms.create({
        message
      } = req.body)
      .then(message => {
        message.addsms(users)
      })
      .then(() => res.status(200).send('OK'))
      // .catch((error) => res.status(400).send(error));
    })
    .catch((error) => res.status(400).send(error));
  }

0 个答案:

没有答案