Laravel添加自定义属性以分页结果

yjghlzjz  于 12个月前  发布在  其他
关注(0)|答案(6)|浏览(92)

我正在尝试将一些数据添加到分页结果中。这是代码:

// query select and filter
[...]

$totalAmount = $sales->sum('amount');
$result = $sales->paginate($rowsPerPage);
return $result;

字符串
结果是:

{
    "datatable": {
        "current_page": 1,
        "data": [
            {
                "sale": 13047689,
                "customer": "0017850000104",
                "date": "2015-12-23 23:15:06",
                "amount": "129.84",
            }
        ],
        "first_page_url": "http://intranet/api/user/sales/datatable?custom=value&page=1",
        "from": 1,
        "last_page": 1,
        "last_page_url": "http://intranet/api/user/sales/datatable?custom=value&page=1",
        "next_page_url": null,
        "path": "http://intranet/api/user/sales/datatable",
        "per_page": "10",
        "prev_page_url": null,
        "to": 1,
        "total": 1
    }
}


我想将totalAmount添加到这个分页对象中。
我所尝试的:

$result->appends('totalAmount', $totalAmount);


我在网上找到了这个方法,但似乎它什么也没做......结果和上面的一样,没有这个属性。
我发现的另一个方法是放。

$result->put('totalAmount', $totalAmount);


这个方法确实有效,但不是我需要的方式。这是为了向结果中添加一些行,因为它在“data”中添加了属性。当我为datatable传递这个结果时,这会破坏我的代码。

{
    "datatable": {
        "current_page": 1,
        "data": {
            "0": {
                "sale": 13047689,
                "customer": "0017850000104",
                "date": "2015-12-23 23:15:06",
                "amount": "129.84",
            },
            "totalAmount": "129.84"
        },
        "first_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "from": 1,
        "last_page": 1,
        "last_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "next_page_url": null,
        "path": "http://intranet/api/user/sales/datatable",
        "per_page": "10",
        "prev_page_url": null,
        "to": 2,
        "total": 1
    }
}


我怎么能这么做?
我喜欢这个:

{
    "datatable": {
        "current_page": 1,
        "data": [
            {
                "sale": 13047689,
                "customer": "0017850000104",
                "date": "2015-12-23 23:15:06",
                "amount": "129.84",
            }
        ],
        "first_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "from": 1,
        "last_page": 1,
        "last_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "next_page_url": null,
        "path": "http://intranet/api/user/sales/datatable",
        "per_page": "10",
        "prev_page_url": null,
        "to": 2,
        "total": 1,
        "totalAmount": "129.84"
    }
}


或者进一步的步骤是:

{
    "datatable": {
        "current_page": 1,
        "data": [
            {
                "sale": 13047689,
                "customer": "0017850000104",
                "date": "2015-12-23 23:15:06",
                "amount": "129.84",
            }
        ],
        "first_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "from": 1,
        "last_page": 1,
        "last_page_url": "http://intranet/api/user/sales/datatable?page=1",
        "next_page_url": null,
        "path": "http://intranet/api/user/sales/datatable",
        "per_page": "10",
        "prev_page_url": null,
        "to": 2,
        "total": 1,
        "totalData": {
            "accumulated1": 235,
            "accumulated2": 799,
            "accumulated3": 1680,
        },
    }
}


有帮助吗?谢谢。

x9ybnkn6

x9ybnkn61#

你需要先为你的响应创建资源,然后像这样添加Meta数据到结果中:

return (new UserCollection(User::all()->load('roles')))
                ->additional(['meta' => [
                    'key' => 'value',
                ]]);

字符串
看看这个

z9gpfhce

z9gpfhce2#

请试着

$result->totalAmount = $totalAmount;

字符串
然后使用$result->totalAmount;访问它。
只是一件东西,应该没什么问题

rur96b6h

rur96b6h3#

试试这个:

$totalAmount = $sales->sum('amount');
$result = $sales->paginate($rowsPerPage);

$custom = collect(['totalAmount' => $totalAmount]);

$data = $custom->merge($result);

字符串

92dk7w1h

92dk7w1h4#

最后弄明白了这一点。如果你试图返回一个json或数组结果,只需先将分页数据改为数组。然后将所需的属性添加到数组中。

$results = $data->paginate()->toArray();
$results['new_attribute'] = 'Attribute Value';
return response()->json($result);

字符串
合并或追加到分页的数据不起作用,因为它在转换为数组时会丢失。

km0tfn4u

km0tfn4u5#

首先,对$sales查询执行分页:

$result = $sales->paginate($rowsPerPage);

字符串
然后,将结果转换为数组:

$result = $result->toArray();


接下来,添加属性:
$result = $sales->sum('amount');

return $result;


总之,您对$sales查询执行分页,将结果转换为数组,通过计算原始$sales查询中的amount字段的总和来添加totalAmount属性,然后返回修改后的结果。
请注意,您应该将$rowsPerPage替换为每页行数的实际值,并调整代码以适合您的特定用例。

cedebl8k

cedebl8k6#

如果你需要它作为一个分页器的结果,你必须实现相应的两个参考资料:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\PaginatedResourceResponse;

class CustomizablePaginatedResourceResponse extends PaginatedResourceResponse
{

    /**
     * Custom attributes.
     *
     * @var array
     */
    protected array $attrs = [];

    /**
     * Add the pagination information to the response.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    protected function paginationInformation($request): array
    {
        $paginated = $this->resource->resource->toArray();
        $paginated['meta'] = $this->attrs;

        return $paginated;
    }

    /**
     * Add attributes.
     *
     * @param array $attrs
     * @return $this
     */
    public function addAttributes(array $attrs): static
    {
        $this->attrs = $attrs;
        return $this;
    }
}

字符串

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;
use Illuminate\Pagination\AbstractPaginator;

class CustomizablePaginatedResource extends ResourceCollection
{

    /**
     * Custom attributes.
     *
     * @var array
     */
    protected array $attrs = [];

    /**
     * Create an HTTP response that represents the object.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function toResponse($request)
    {
        if (!($this->resource instanceof AbstractPaginator)) {
            throw new \RuntimeException('Only AbstractPaginator is accepted');
        }

        return (new CustomizablePaginatedResourceResponse($this))
            ->addAttributes($this->attrs)
            ->toResponse($request);
    }

    /**
     * Add custom attribute.
     *
     * @param string $key
     * @param mixed $value
     * @return $this
     */
    public function addAttribute(string $key, mixed $value): static
    {
        $this->attrs[$key] = $value;
        return $this;
    }

    /**
     * Remove attribute.
     *
     * @param string $key
     * @return $this
     */
    public function delAttribute(string $key): static
    {
        unset($this->attrs[$key]);
        return $this;
    }

}


现在,在你的控制器中,你已经将分页示例封装到资源中,如下面的例子所示:

return (new CustomizablePaginatedResource($qry->paginate()))
            ->addAttribute('my_attribute1', 'foo')
            ->addAttribute('my_attribute2', 'bar');


分页会将属性添加到位于根目录的“Meta”属性中。您可以自由自定义资源以更改根属性名称。

相关问题