根据请求环回发送关系数据
Loopback send relation data on request
在环回中,我们有模型关系。
这是一个示例模型
{
id: "gdfgd",
name: "companyname",
ownerId: "userId",
}
当使用 get 端点请求时,响应是这样的。
但是有没有办法使环回解析这些 ID 并发回嵌入在响应中的实际用户数据?
像这样
{
id: "gdfgd",
name: "companyname",
ownerId: {
id: "hhrtgrt",
username: "username",
email: "ggg@ggg.gg"
},
}
您也应该检查 docs (include relations) about the relations in loopback, especially include filter. You can include a relationship in your request, for example, if you have a List model and a Task model, then you can have Task belongsTo List
relationship and List hasMany Task
relationship. You can check how to define those relationships in docs (relations)。
// model: List
...
"relations": {
"tasks": {
"type": "hasMany",
"model": "Task",
"foreignKey": ""
}
}
// model: Task
...
"relations": {
"list": {
"type": "belongsTo",
"model": "List",
"foreignKey": ""
}
}
当您正确定义模型之间的关系时,您的 GET 请求可能如下所示:
localhost:3000/api/List?filter[include]='tasks' // get all lists with all tasks - each list will have all its tasks
或
localhost:3000/api/Task?filter[include]='list' // get all tasks with their list - each task will have its parent list
总的来说,loopback doc 是开始旅程的好地方,他们给出了很多例子并且描述得很好。
在环回中,我们有模型关系。 这是一个示例模型
{
id: "gdfgd",
name: "companyname",
ownerId: "userId",
}
当使用 get 端点请求时,响应是这样的。
但是有没有办法使环回解析这些 ID 并发回嵌入在响应中的实际用户数据?
像这样
{
id: "gdfgd",
name: "companyname",
ownerId: {
id: "hhrtgrt",
username: "username",
email: "ggg@ggg.gg"
},
}
您也应该检查 docs (include relations) about the relations in loopback, especially include filter. You can include a relationship in your request, for example, if you have a List model and a Task model, then you can have Task belongsTo List
relationship and List hasMany Task
relationship. You can check how to define those relationships in docs (relations)。
// model: List
...
"relations": {
"tasks": {
"type": "hasMany",
"model": "Task",
"foreignKey": ""
}
}
// model: Task
...
"relations": {
"list": {
"type": "belongsTo",
"model": "List",
"foreignKey": ""
}
}
当您正确定义模型之间的关系时,您的 GET 请求可能如下所示:
localhost:3000/api/List?filter[include]='tasks' // get all lists with all tasks - each list will have all its tasks
或
localhost:3000/api/Task?filter[include]='list' // get all tasks with their list - each task will have its parent list
总的来说,loopback doc 是开始旅程的好地方,他们给出了很多例子并且描述得很好。