Men*_*nds 6 strongloop loopbackjs
我有两个通过hasMany关系相关的模型.
Customer
有很多 CustomerPhones
在创建新内容时Customer
,我想将相关内容CustomerPhones
作为单个请求的一部分传递.这似乎是一种常见的需求,如果我想要实现的方法是错误的,那么这样做的首选方法是什么?
这是创建客户的URL: POST /api/Customers
上面url的请求将是req.body
{
"name": "Foo",
"customerPhones": [
{ "phoneNumber": "8085551234" },
{ "phoneNumber": "8085554567" }
]
}
Run Code Online (Sandbox Code Playgroud)
Loopback模型配置:
Customer.json
{
"name": "Customer",
"base": "User",
"properties": {
"name": {
"type": "string",
"required": true
}
},
"relations": {
"customerPhones": {
"type": "hasMany",
"model": "CustomerPhone",
"foreignKey": ""
}
}
}
Run Code Online (Sandbox Code Playgroud)
CustomerPhone.json
{
"name": "CustomerPhone",
"base": "PersistedModel",
"properties": {
"phoneNumber": {
"type": "string",
"required": true
},
"customerId": {
"type": "number",
"required": true
}
},
"relations": {
"customer": {
"type": "belongsTo",
"model": "Customer",
"foreignKey": "customerId"
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 NoSQL 数据库连接器,那么您可以忽略另一个CustomerPhone
模型并将customerPhones
属性作为数组添加到Customer
模型中。
POST /api/Customers
另外,对于 SQL 数据库连接器,您可以创建一个同时执行和的远程方法POST /api/Customers/id/CustomerPhones
。对于多个电话号码,您可以迭代req.bodycustomerPhones
中的字段并每次执行。POST /api/Customers/id/CustomerPhones
归档时间: |
|
查看次数: |
1380 次 |
最近记录: |