我正在尝试使用带关联的模型。我有两个模型定义如下:
user.js的
module.exports = {schema: true, attributes: {
userId: {
autoIncrement: true,
type: integer,
primaryKey: true,
},
userId: {type: integer},
email: {type:string, size:200},
addressId: {
model:UserAddress
}
}
Address.js
module.exports = {schema: true, attributes: {
addressId: {
autoIncrement: true,
type:integer,
primaryKey:true
},
userId: {type:integer},
address: {type:string, size:250}
}
到目前为止,我能够通过POST跟随JSON到
来在两个模型中创建记录http://localhost:1337/user/
{
"userName": "John",
"userId": "3",
"email":"john@hotmail.com",
"addressId": {
"userId": "3",
"address": "123 abc street"
}
}
我能够使用此URL使用PUT更新两个记录:
下面是http://localhost:1337/user/update/1
和JSON,请注意我在这种情况下在嵌套的JSON中添加了 addressId 。
{
"userName": "John",
"userId": "3",
"accountLogin":"john@hotmail.com",
"addressId": {
"addressId":1,
"userId": "3",
"streetAddress": "123 abc street"
}
}
然而,当我第一次在User表中创建一个没有地址的记录,后来想要添加它时,我没有运气让它工作。我所做的是使用PUT对http://localhost:1337/user/update/1
跟随JSON,因为地址是新的,没有addressId。
{
"userName": "John Doe",
"accountLogin":"john@hotmail.com",
"addressId": {
"userId": "3",
"streetAddress": "123 abc street"
}
}
有没有办法在Sails.js做我想做的事情?我可以发帖到http://localhost:1337/address
创建一个新记录,但我想让我的API保持一致。更严重的问题是,当发送上面的JSON时,它会崩溃后端。在我看来,用户可以通过发送无效的JSON轻松崩溃后端,我如何保护后端免受这种崩溃?
答案 0 :(得分:1)
Hy,
为了将新对象添加到对象内的集合中,您可以使用内置的风帆(蓝图)"添加"方法。我检查了网站上的sails文档但是没有成功,但是如果你检查github存储库中的add
蓝图,那么它确实是你所期待的。
以下是方法说明:
/**
* Add Record To Collection
*
* post /:modelIdentity/:id/:collectionAttr/:childid
* * /:modelIdentity/:id/:collectionAttr/add/:childid
*
* Associate one record with the collection attribute of another.
* e.g. add a Horse named "Jimmy" to a Farm's "animals".
* If the record being added has a primary key value already, it will
* just be linked. If it doesn't, a new record will be created, then
* linked appropriately. In either case, the association is bidirectional.
*
* @param {Integer|String} parentid - the unique id of the parent record
* @param {Integer|String} id [optional]
* - the unique id of the child record to add
* Alternatively, an object WITHOUT a primary key may be POSTed
* to this endpoint to create a new child record, then associate
* it with the parent.
*
* @option {String} model - the identity of the model
* @option {String} alias - the name of the association attribute (aka "alias")
*/
回答你的下一个问题是,还有一个删除方法;)
您可以在那里找到更多信息:https://github.com/balderdashy/sails/tree/master/lib/hooks/blueprints/actions