如何在 laravel 资源中添加订单字段?

Posted

技术标签:

【中文标题】如何在 laravel 资源中添加订单字段?【英文标题】:How in laravel resources to add order field? 【发布时间】:2021-01-30 22:57:31 【问题描述】:

在 laravel 7 应用程序中,我在控制器中使用集合:

return (new TaskCollection($tasks));

和 app/Http/Resources/TaskCollection.php

<?php

namespace App\Http\Resources;
use App\Facades\MyFuncsClass;
use App\Task;

use Illuminate\Http\Resources\Json\ResourceCollection;

class TaskCollection extends ResourceCollection

    public static $wrap = 'tasks';
    public function toArray($request)
    
        return $this->collectResource($this->collection)->transform(static function (Task $task)
                return [
                    'id' => $task->id,
                    ....
                    'created_at' => $task->created_at,
                    'updated_at' => $task->updated_at,
                    'deleted_at' => $task->deleted_at,
                ];
            );

    

    public function with($request)
    
        return [
            'meta' => [
               ...
            ]
        ];
    


我需要在下一行添加订单字段(从 0 值)+ 1。我该怎么做?

谢谢!

【问题讨论】:

【参考方案1】:

使用map函数:

public function toArray($request)

    $this->collection = $this->collection->map(function ($item, $key) 
        $item['order'] = $key;
        return $item;
    );

    return $this->collectResource($this->collection)->transform(static function (Task $task)
        return [
            'id' => $task->id,
            'order' => $task->order,
                ....
            'created_at' => $task->created_at,
            'updated_at' => $task->updated_at,
            'deleted_at' => $task->deleted_at,
        ];
   );


【讨论】:

以上是关于如何在 laravel 资源中添加订单字段?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Shopware 6 中为订单添加自定义字段?

如何在 Woocommerce 购物车页面中添加订单备注字段?

Laravel - 如何在忘记密码中添加自定义字段

Laravel如何在查询结果中添加新字段

如何在背包-laravel 的注册表单中添加更多字段?

如何在 laravel 的导航栏列表中添加路由资源?