php Laravel资源集合,将数据从资源返回到集合

lstz6jyr  于 2023-02-07  发布在  PHP
关注(0)|答案(2)|浏览(138)

我正在使用Laravel v6编写资源和资源集合。我希望使用资源集合内部资源的一些数据。例如,我有以下UserResourceUserCollection

class UserResource extends JsonResource
{
    public $data = 0;
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $this->data + = 5; 
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
    public function getAdditionalData(){
            return $this->data;
    }
}

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'additional-data' => [
                (new UserResource(null))->getAdditionalData(),
            ],
        ];
    }
}

我想返回一些在资源中计算的数据,并在资源集合中使用它。我收到的值是0,而我期望的是5。我如何将这些数据从资源返回到集合中?

ma8fv8wu

ma8fv8wu1#

您尚未调用资源的toArray()函数,因此data不会递增。请尝试首先调用该函数,例如:

$userResource = new UserResource(null);
$userResource->toArray(); // Returns an array. Your data is incremented here
$additionalData = $userResource->getAdditionalData(); // what you actually want

如果你能提供一个更大的图景来描述你正在努力做的事情,那会很有帮助。

zujrkrfu

zujrkrfu2#

**Use this method in Collection below toArray Method**

public function toArray($request) {
    return $this->collection;
}

public function withResponse($request, $response) {
    $jsonResponse = json_decode($response->getContent());
    $jsonResponse->settings = array_values(ResponseManager::getResult('', $this->status, $this->message, $this->code))[0];

    if (isset($jsonResponse->links) && isset($jsonResponse->meta)) {
        unset($jsonResponse->links);
    }

    $response->setContent(json_encode($jsonResponse));
}

相关问题