表:联系人,公司和具有自定义透视属性的关系表company_contact(company_id,contact_id,is_main)
公司和联系人有多对多的关系(属于两个型号).
检索公司联系人时的预期输出:
{
"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,我所做的所有调用(与联系人相关或不相关)也会期望该属性.
解决方法:
如果我正确地读了你,你可以利用一个CompanyTransformer来处理你是否希望设置is_main属性,但只有将$contact参数传递给它的构造函数时才会这样做:
class CompanyTransformer extends TransformerAbstract
{
public function __construct(Contact $contact = null)
{
$this->contact = $contact;
}
public function transform(Company $company)
{
$output = [
'id' => $company->id,
'name' => $company->name,
];
if($this->contact) {
// This step may not be necessary, but I don't think the pivot data
// will be available on the $company object passed in
$company = $this->contacts->find($company->id);
// You may have to cast this to boolean if that is important
$output['is_main'] = $company->pivot->is_main;
}
return $output;
}
}
然后在includeCompanyRelationship中,只需使用参数传入新的CompanyTransformer:
public function includeCompanyRelationship(Contact $contact)
{
$companies = $contact->companies;
return $this->collection($companies, new CompanyTransformer($contact));
}
无论您是直接呼叫公司端点,还是在嵌入公司关系数据时调用联系人的端点,这都应该有效.