【发布时间】:2015-12-18 06:33:54
【问题描述】:
表:contact、company 和带有自定义透视属性的关系表 company_contact (company_id, contact_id, is_main)
Company 和 Contact 具有多对多关系(belongsTo 在两种模型上)。
检索公司联系人时的预期输出:
{
"data": [
{
"id": 1,
"name": "JohnDoe",
"is_main": false
},
{
"id": 2,
"name": "JaneDoe",
"is_main": true
}
]
}
当我使用?include=companies 检索联系人列表时的预期输出:
{
"data": [
{
"id": 1,
"name": "John Doe",
"companies": {
"data": [
{
"id": 501,
"name": "My Company",
"is_main": true
},
{
"id": 745,
"name": "Another Company",
"is_main": false
}
]
}
},
{
"id": 2,
"name": "Jane Doe",
"companies": {
"data": [
{
"id": 999,
"name": "Some Company",
"is_main": true
}
]
}
}
]
}
添加数据透视表属性的最佳方法是什么?如果设置了属性,在公司转换器上添加is_main似乎不是很干净。
对于第一个示例,我正在考虑使用参数?include=company_relationship:company_id(1),例如:
public function includeCompanyRelationship(Contact $contact, ParamBag $params) {
// .. retrieve the pivot table data here
$is_main = $company->is_main;
// but now I would need another transformer, when what I actually want is to push the value on the main array (same level)
return $this->item(??, ??);
}
我了解如何检索数据透视数据(相关:Laravel 5.1 - pivot table between three tables, better option?),但不是在https://github.com/thephpleague/fractal Transformer 逻辑中添加它的最佳方式。
我已经有一个 ContactTransformer 和 CompanyTransformer,但是如果我将 is_main 添加到 CompanyTransformer 我所做的所有呼叫(与联系人相关或不与联系人相关)也将期望该属性。
【问题讨论】:
标签: php api laravel-5.1 thephpleague thephpleague-fractal