如何在laravel资源中添加订单字段?
How in laravel resources to add order field?
在 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。我该怎么做?
谢谢!
使用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 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。我该怎么做?
谢谢!
使用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,
];
});
}