分形变压器Laravel?

时间:2017-05-09 07:31:18

标签: laravel laravel-5 laravel-5.4

我试图将对象转换为:

$objects = Object::all();
$objects = (new ObjectTransformer)->transform($objects);

ObjectTransformer的位置:

class ObjectTransformer extends TransformerAbstract {

    public function transform(Object $obj)
    {
        return [
            'id' => (int) $obj->id,
            'name' => $obj->prefix
        ];
    }
}

我收到错误:

Type error: Argument 1 passed to App\Http\Controllers\API\ObjectTransformer::transform() must be an instance of App\Http\Controllers\API\Object, instance of Illuminate\Database\Eloquent\Collection given

1 个答案:

答案 0 :(得分:0)

该函数需要Object,并且您传递Collection Objects ...

但是如果你想要的只是转换一个集合,你就不需要创建一个特定的类,只需使用transform Collection方法和一个完成这项工作的匿名函数:

$objects = Object::all();
$objects->transform(function($object,$key){
    return [
        'id'=>(int)$object->id, 
        'name'=>$object->prefix
    ];
});