如何在 Loopback 中使用带有外键的 hasAndBelongsToMany 模型
How to use hasAndBelongsToMany models with foreign key in Loopback
我有客户和组模型:
每个客户可能属于多个组,而每个组可能有多个客户。
我想在他们之间建立关系。
我为两个模型都添加了 hasAndBelongsToMany
。我的目标是在使用 API 时,如果我像这样发送 url,我将能够包括客户所属的所有组:/api/Customers
、
它会 return [{name: xxx, groups: ['northeast','northwest']},{name: xxx, groups: ['northeast']}]
.
如何在 model.json
中配置这样的东西?
// Customer Model
{
"name": "Customer",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
}
"groupId": {
"type": "array" // not sure what to do.
}
},
"validations": [],
"relations": {
"groups": {
"type": "hasAndBelongsToMany",
"model": "Group",
"foreignKey": "customerId"
}
},
"acls": [],
"methods": {}
}
// Group Model
{
"name": "Group",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"label": {
"type": "string"
}
},
"validations": [],
"relations": {
"customers": {
"type": "hasAndBelongsToMany",
"model": "Customer",
"foreignKey": "groupId"
}
},
"acls": [],
"methods": {}
}
无需向模型定义添加内容。
就在 API 调用中添加 include
比如:/api/Customers?filter[include]=groups
以下不是必须的,您可以将其从模型定义中删除:
"groupId": {
"type": "array" // not sure what to do.
}
我有客户和组模型:
每个客户可能属于多个组,而每个组可能有多个客户。
我想在他们之间建立关系。
我为两个模型都添加了 hasAndBelongsToMany
。我的目标是在使用 API 时,如果我像这样发送 url,我将能够包括客户所属的所有组:/api/Customers
、
它会 return [{name: xxx, groups: ['northeast','northwest']},{name: xxx, groups: ['northeast']}]
.
如何在 model.json
中配置这样的东西?
// Customer Model
{
"name": "Customer",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
}
"groupId": {
"type": "array" // not sure what to do.
}
},
"validations": [],
"relations": {
"groups": {
"type": "hasAndBelongsToMany",
"model": "Group",
"foreignKey": "customerId"
}
},
"acls": [],
"methods": {}
}
// Group Model
{
"name": "Group",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"label": {
"type": "string"
}
},
"validations": [],
"relations": {
"customers": {
"type": "hasAndBelongsToMany",
"model": "Customer",
"foreignKey": "groupId"
}
},
"acls": [],
"methods": {}
}
无需向模型定义添加内容。
就在 API 调用中添加 include
比如:/api/Customers?filter[include]=groups
以下不是必须的,您可以将其从模型定义中删除:
"groupId": {
"type": "array" // not sure what to do.
}