0

尝试将电话号码与用户关联会导致节点告诉我用户对象没有方法 addPhonenumber。(也发生在 setPhonenumber 上)

req.user.setPhonenumbers(phonenumber).success(function(user){
             ^
TypeError: Object [object Object] has no method 'setPhonenumbers'

如何正确关联对象?代码如下。

models.js 中的对象定义:

exports.User = require("./user")(sequelize, Sequelize);
exports.Phonenumber = require("./phonenumber")(sequelize, Sequelize);
exports.Recording = require("./recording")(sequelize, Sequelize);
exports.Call = require("./call")(sequelize, Sequelize);

User
  .hasMany(Phonenumber)
  .hasMany(Recording);

Phonenumber
  .belongsTo(User)
  .hasOne(Recording)
  .hasMany(Call);

Recording.belongsTo(User);

Call.belongsTo(Phonenumber);

尝试设置关联:

      var phonenumber = yp.db.Phonenumber.create({
        number: number.phone_number
      }).success(function(number){
        console.log(number);
        console.log(req.user);
        req.user.setPhonenumbers(phonenumber).success(function(user){
          console.log(user);
        });
      });

以及上面引用的req.user的console.log结果:

{ __options: 
   { timestamps: true,
     instanceMethods: { fullname: [Function] },
     classMethods: {},
     validate: {},
     freezeTableName: false,
     underscored: false,
     syncOnAssociation: true,
     paranoid: true,
     omitNull: false,
     hasPrimaryKeys: false },
  hasPrimaryKeys: false,
  selectedValues: 
   { firstname: 'Nathan',
     lastname: 'Loyer',
     email: 'xxx@gmail.com',
     password: '****',
     facebookid: '****',
     id: 2,
     createdAt: Thu Feb 28 2013 20:40:29 GMT-0600 (CST),
     updatedAt: Wed Mar 06 2013 20:22:05 GMT-0600 (CST),
     deletedAt: null },
  firstname: 'Nathan',
  lastname: 'Loyer',
  email: 'xxx@gmail.com',
  password: '****',
  facebookid: '****',
  id: 2,
  createdAt: Thu Feb 28 2013 20:40:29 GMT-0600 (CST),
  updatedAt: Wed Mar 06 2013 20:22:05 GMT-0600 (CST),
  deletedAt: null,
  isNewRecord: false }

我错过了什么?

谢谢!

4

2 回答 2

1

你的每个 hasMany 都需要一个匹配的 belongsTo。并且,关联的函数将是 setPhonenumbers。请参阅:http ://www.sequelizejs.com/documentation#associations-associating-objects

于 2013-04-06T01:15:48.900 回答
0

原来这是我的命名不够严格的问题。在 phonenumber 模型的模型定义中,我使用 Number 而不是 Phonenumber。

module.exports = function(sequelize, Sequelize){

  return sequelize.define('Number',{
    number: Sequelize.STRING,
  },{
    paranoid: true
  });

}

所以它创建了一个 setNumbers 函数,而不是 setPhonenumbers 函数。改为将其更改为 Phonenumber 并重新创建表格使上述代码几乎可以工作。setPhonenumbers 似乎想要一个数组,所以我用 addPhonenumber 代替。

于 2013-04-10T17:37:01.703 回答