我有客户和群组模型:
每个客户可能属于多个组,而每个组可能有多个客户。
我想建立他们之间的关系。
我在两个模型中添加了hasAndBelongsToMany
。我的目标是在使用API时,如果我发送这样的网址,我将能够包含客户所属的所有群组:/api/Customers
,
它将返回[{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": {}
}

答案 0 :(得分:2)
无需向模型定义添加内容。
只需在API调用中添加include
,例如:/api/Customers?filter[include]=groups
以下不是必需的,您可以将其从模型定义中删除:
"groupId": {
"type": "array" // not sure what to do.
}