I'm a bit confused about the belongsTo relation function of loopback.io
So let's take the following example:
I have a model called Project which has a relation to a Customer object. So a Project belongs to a Customer.
This is my Project model
{
"name": "Project",
"plural": "Projects",
"base": "PersistedModel",
"strict": false,
"idInjection": false,
"options": {
"validateUpsert": true
},
"properties": {
"title": {
"type": "string",
"required": true
},
"description": {
"type": "string"
},
"dateCreated": {
"type": "date"
}
},
"validations": [],
"relations": {
"customer": {
"type": "belongsTo",
"model": "Customer",
"foreignKey": "customerId"
}
},
"acls": [],
"methods": {}
}
So when I run the app and I go to http://0.0.0.0:3000/explorer I can see the API. But When I go to project I only see
GET /Projects/{id}/customer Fetches belongsTo relation customer.
I was also expecting other functions like
POST /Projects/{id}/customer
DELETE /Projects/{id}/customer
Why are they not available here? Or how can I set the customer for a project via REST API?
Let's first understand belongsTo relationship, to understand why only GET rest endpoint is created:
GET /Projects/{id}/customer Fetches belongsTo relation customer.
And why Loopback didn't created the below links:
POST /Projects/{id}/customer
DELETE /Projects/{id}/customer
belongsTo
relationship creates a one-to-one relation between two model instance. It is used to provide ownership of one instance to another instance. In your case, project model instance belongs to a customer model instance. Now since project belongs to customer, therefore customer owns the project instance and so explanation for the rest endpoints.
GET /Projects/{id}/customer Fetches belongsTo relation customer.
since customer can have project instance, therefore above is valid as customers can be fetched for projects.
POST /Projects/{id}/customer
DELETE /Projects/{id}/customer
since customer don't belong to a project rather has project, above rest endpoints doesn't make sense as projects creating or disowning its owner(customer).