我注意到我没有在帖子中获得与我获得的相同回复。具体来说,协会。sails.js创建为单向关联的一对一关联
参照“创建新的记录,而关联瓦特/另一个新纪录” https://github.com/balderdashy/sails-docs/blob/master/reference/blueprint-api/Create.md
我重新场景从sails new testProj
,然后sails generate api pony
和sails generate api pet
的文档,然后更新模型有一个一对一协会。
小马
module.exports = {
attributes: {
pet: {
model: 'pet'
}
}
};
小马
module.exports = {
attributes: {
pet: {
model: 'pet'
}
}
};
宠物
module.exports = {
attributes: {
pony: {
model: 'pony'
}
}
};
然后,sails lift
之遥。
POST /pony
JSON询价
{
"name": "Pinkie Pie",
"hobby": "ice skating",
"pet": {
"name": "Gummy",
"species": "crocodile"
}
}
JSON RES
{
"name": "Pinkie Pie",
"hobby": "ice skating",
"pet": 1,
"createdAt": "2014-11-21T19:18:09.161Z",
"updatedAt": "2014-11-21T19:18:09.161Z",
"id": 1
}
正如你所看到的,res
ponse不包括完整的宠物对象,只是它的ID。在文档中,它显示了正在返回的完整对象。
的条目和协会肯定了创建成功,
GET - /pony/1
{
"pet": {
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-11-21T19:18:09.157Z",
"updatedAt": "2014-11-21T19:18:09.157Z",
"id": 1
},
"name": "Pinkie Pie",
"hobby": "ice skating",
"createdAt": "2014-11-21T19:18:09.161Z",
"updatedAt": "2014-11-21T19:18:09.161Z",
"id": 1
}
这是在文档中的错误,或在代码中的错误?无论哪种方式,有没有一种方法可以指定我们想要返回关联?
一对一关联只是显示为链接标识,多数人根本没有显示出来。当我看到showJoins
选项时,我正在调查waterline
的另一个问题toObject()
函数;它看起来可能与此有关。
此外,此一对一关联实际上只是作为单向关联创建的。
完成与上述相同的后:
GET - /pet/1
{
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-12-03T20:50:31.346Z",
"updatedAt": "2014-12-03T20:50:31.346Z",
"id": 1
}
注意,没有返回小马。
只是为了确保...
GET - /pony/1/pet
{
"name": "Gummy",
"species": "crocodile",
"createdAt": "2014-12-03T20:50:31.346Z",
"updatedAt": "2014-12-03T20:50:31.346Z",
"id": 1
}
GET - /pet/1/pony
Res
Specified record (1) is missing relation 'pony'
小马有一个宠物,宠物有没有小马。
我做错了什么?
不适用于一对多。 – 2015-05-02 00:13:56
你不需要'via'进行一对一的关联https://github.com/balderdashy/waterline-docs/blob/master/models/associations/one-to-one.md – dkx22 2015-08-18 15:35:48
one-一对一关联只能从持有外键的模型中工作。有关更多信息,请参阅http://stackoverflow.com/a/27752329/129808。 – oldwizard 2015-08-21 12:34:02