laravel 将API资源转换为数组

voj3qocg  于 2022-12-14  发布在  其他
关注(0)|答案(2)|浏览(192)

我想在Firestore上存储数据。我需要向Firestore发送一个数组。我有API资源,我想使用它。
我的ApiResource:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'phone' => $this->phone,
        'addresses' => AddressResource::collection($this->addresses),
    ];
}

Firestore存储数据:

public function set(User $user){
    $this->firestore->document($user->id)->set((new UserResource($user)));
}

这是一个错误:
传递给Google\Cloud\Firestore\DocumentReference::set()的参数1必须是数组、给定对象、...

rqenqsqc

rqenqsqc1#

您可以在API资源对象上调用toJson()

$data = MyModel::with('addresses')->find(1);

$myArray = json_decode((new MyModelResource($data))->toJson(), true);

因此,您只需:

$this->firestore->document($user->id)->set($myArray);
wfsdck30

wfsdck302#

请执行以下操作:

public function set(User $user){
    $this->firestore->document($user->id)->set(toArray($user)); 
}

相关问题