I have two models that are related through a hasMany relationship.
Customer
hasMany CustomerPhones
When creating a new Customer
, I would like to pass the related CustomerPhones
as part a single request. This seems like a common need, if the approach I am looking to implement in wrong, what is the preferred way of doing this?
This is the url for creating a customer: POST /api/Customers
The request for above url would be req.body
{
"name": "Foo",
"customerPhones": [
{ "phoneNumber": "8085551234" },
{ "phoneNumber": "8085554567" }
]
}
Loopback models configurations:
Customer.json
{
"name": "Customer",
"base": "User",
"properties": {
"name": {
"type": "string",
"required": true
}
},
"relations": {
"customerPhones": {
"type": "hasMany",
"model": "CustomerPhone",
"foreignKey": ""
}
}
}
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"
}
}
}