Laravel 5.1和Fractal:包括变压器上的数据透视表数据

时间:2015-09-21 14:03:01

标签: php api laravel-5.1 thephpleague thephpleague-fractal

表:contactcompany以及包含自定义透视属性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
                    }
                ]
            }
        }
    ]
}

添加数据透视表属性的最佳方法是什么?如果设置了属性,在公司变换器上添加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变换器逻辑中添加数据的最佳方法。

我已经有了一个ContactTransformer和CompanyTransformer但是如果我将is_main添加到CompanyTransformer,我所做的所有电话(与联系人相关或不相关)都会期望该属性。

2 个答案:

答案 0 :(得分:3)

如果我正确地阅读了您,您可以使用单个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端点,还是在嵌入公司关系数据时呼叫联系人的端点,这都应该有效。

答案 1 :(得分:2)

我知道这已经过时了,但我刚遇到这个问题。以下是我如何解决它。

在我的案例Library_Kinddynamic中为关系添加了Library_Standalone

在CategoryTransformer中,我定义了withPivot方法:

category

然后在users课程中,使用includeUsers方法:

/**
 * Include Users
 * @param Category $category
 * @return \League\Fractal\Resource\Collection
 */
 public function includeUsers(Category $category)
 {
     # Just Add withPivot Here.
     $users = $category->users()->withPivot('role')->get();
     return $this->collection($users, new UserTransformer);
 }

然后,当我为UserTransformer打电话给我的api并包含transform()时,我得到了:

public function transform($user)
{
    return [
        'username' => $user['username'],
        'lastname' => $user['lastname'],
        // ... truncated
        'role' => isset($user['pivot']) ? $user['pivot']['role'] : null,
    ]
}

如您所见,我从枢轴中获得了我想要的categories关系。否则,您只需获得users该字段。在我看来,仍然不理想,但不那么混乱。