3

为了改变 Laravel 5.4 RESTful API 发送的 JSON 输出,我使用了 thephpleague 的 Fractal 包。因为将来会添加分页,所以集合使用默认的 DataArraySerializer 并且单个项目使用 ArraySerializer 很重要。还需要为更深的嵌套对象赋予相同的结构。我怎样才能实现这一点(全球或不)?

class TreeTransformer extends TransformerAbstract {
    protected $defaultIncludes = [
        'type',
        'branches'
    ];

    public function transform(Tree $tree) {
         return [
            'id' => (int)$tree->id,
            'name' => (string)$tree->name
        ];
    }

    public function includeType(Tree $tree) {
        return $this->item($tree->type, new TypeTransformer()); // Should be ArraySerializer  
    }

    public function includeBranches(Tree $tree) {
        return $this->collection($tree->branches, new BranchTransformer()); // Should stay DataArraySerializer  
    }
}
4

2 回答 2

2

其实你可以。它可能看起来更冗长,但诀窍就是不使用$defaultIncludes. 请改用分形助手。

class TreeTransformer extends TransformerAbstract {

    public function transform(Tree $tree) {
         return [
            'id' => (int)$tree->id,
            'name' => (string)$tree->name,
            'type' => $this->serializeType($tree)
            'branches' => $this->serializeBranches($tree)
        ];
    }

    private function serializeType(Tree $tree) {
        return fractal()
                ->serializeWith(new ArraySerializer())
                ->collection($tree->type)
                ->transformWith(TypeTransformer::class)
                ->toArray(); // ArraySerializer  
    }

    private function serializeBranches(Tree $tree) {
        return fractal()
                ->serializeWith(new DataArraySerializer())
                ->collection($tree->branches)
                ->transformWith(BranchesTransformer::class)
                ->toArray(); // DataArraySerializer  
    }
}

它对我有用ArraySerializer。没试过DataArraySerializer

于 2018-08-04T17:19:32.110 回答
2

不幸的是,我认为你正在尝试做的事情还不可能。更多信息在这里:https ://github.com/thephpleague/fractal/issues/315

您仍然可以像这样更改整个输出的序列化程序:https ://github.com/spatie/fractalistic#using-a-serializer 。但这不是你想要达到的。

于 2017-06-02T15:46:11.857 回答