【问题标题】:sails js many to many associations not working帆 js 多对多关联不起作用
【发布时间】:2017-12-24 08:46:33
【问题描述】:

用户.js

module.exports = {
  tableName: 'user',

  attributes: {
    firstName: {
      type: 'string',
    },
    lastName: {
      type: 'string',
    },
    id: {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true
    },
    pets: {                     //integer
     collection:'pet',
     via:'owners'
    }
  }
};

=================================

Pet.js
------
module.exports = {
  tableName: 'pet',

  attributes: {
    id: {
      type: 'integer',
      autoIncrement: true,
      primaryKey: true
    },
    breed: {
      type: 'string',
    },
    type: {
      type: 'string',
    },
    name: {
      type: 'string',
    },
    owners: {                    //integer 
      collection:'user',
      via:'pets'
    }
  }
};

但是当我点击蓝图 API http://localhost:1337/userhttp://localhost:1337/pet 时,我没有得到相关记录

这是用户和宠物在 ARC 或邮递员中的输出

[
  {
"pets": [],
"firstName": "a",
"lastName": "aa",
"id": 1
},
  {
"pets": [],
"firstName": "b",
"lastName": "bb",
"id": 2
},
  {
"pets": [],
"firstName": "c",
"lastName": "cc",
"id": 3
},
  {
"pets": [],
"firstName": "d",
"lastName": "dd",
"id": 4
},
  {
"pets": [],
"firstName": "e",
"lastName": "ee",
"id": 5
}
],


[
  {
"owners": [],
"id": 1,
"breed": "dalmatian",
"type": "male",
"name": "tom"
},
  {
"owners": [],
"id": 2,
"breed": "labrador",
"type": "female",
"name": "kg"
},
  {
"owners": [],
"id": 3,
"breed": "doberman",
"type": "male",
"name": "tq"
},
  {
"owners": [],
"id": 4,
"breed": "puppy",
"type": "male",
"name": "yu"
}
]

一对多关联工作正常,但不知道我在多对多中缺少什么? 我尝试从两个模型中删除 id 列,但这没有帮助

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    尝试使用add Blueprint API 将宠物添加给所有者:

    POST /:model/:id/:association/:fk
    

    例子:

    http://localhost:1337/user/1/pets/2
    

    这会将 id 为 2 的宠物添加给 id 为 1 的主人。

    【讨论】:

    • 我尝试使用 add 方法 User.findOne(1).exec(function(err, user) { if (err) // 处理错误 // 排队插入连接表的记录user.pets.add(2); // 保存用户,在连接表中创建新的关联 user.save(function(err) { console.log(err) }); 但仍然得到相同的响应 也尝试过使用post方法直接使用邮递员localhost:1337/user/1/pets/2点击,但收到错误“消息”:“[错误(E_UNKNOWN)遇到意外错误]”,
    • 使用此代码在控制台中显示什么?User.findOne(1).populateAll().then(function(user){ sails.log.debug(user); }).catch(function(err){ sails.log.error(err); });
    • 我添加了上面的代码,这是响应调试:{ pets: [], firstName: 'a', lastName: 'aa', id: 1 } 我应该使用 populateall() 吗?因为它应该直接使用 blueprint /user right ?
    • 我在打蓝图 api 仍然在所有者中为宠物和用户中的宠物获取空对象
    猜你喜欢
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多