表:contact
,company
和具有自定义透视属性的关系表company_contact (company_id, contact_id, is_main)
公司和联系人有多对多的关系(在两种型号上都是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
}
]
}
}
]
}
添加透视表属性的最佳方法是什么?如果设置了属性,那么在company transformer上添加
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(??, ??);
}
我了解如何检索pivot数据(相关:Laravel 5.1 - pivot table between three tables, better option?),但不是将其添加到https://github.com/thephpleague/fractaltransformer逻辑中的最佳方式。
我已经有了一个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));
}
无论您是直接调用
companies
端点,还是在嵌入公司关系数据时调用联系人的端点,这都应该有效。关于php - Laravel 5.1和Fractal:包括变压器上的数据透视表数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32697260/