使用Resource的Laravel条件数组

时间:2018-04-12 10:57:26

标签: laravel

我的人员表中有列:personnametext。 列人员只能包含以下值:physiciandentistnurse等...

我想使用Laravel资源通过api发送它,所以我创建了基本的PeopleResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class PeopleResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'text' => $this->text
        ];
    }
}

这很简单,给我一个带有名称和文字的对象数组。

现在我想制作更复杂的数组,它会给我这样的东西:

Please note我想在这里将所有人类型都放入我的数组中。这是使我的数组结构化的问题 - 所以我可以像result.physician.name,result.nurse.name等那样访问它。

result: {
 physician: [{name: "name1", text: "text2"}, {name: "name2", text: "text2"}...],
 nurse: [{name: "name1", text: "text2"}, {name: "name2", text: "text2"}...],
 dentist: [{name: "name1", text: "text2"}, {name: "name2", text: "text2"}...],
 otherTypeOfPerson: [], ....
}

如何使用Laravel资源进行操作?

编辑:我的控制器

<?php

namespace App\Http\Controllers;

use App\People;
use Illuminate\Http\Request;
use App\Http\Resources\PeopleResource;

class PeoplesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $peoples= People::orderBy('id','asc')->get();

        return PeopleResource::collection($peoples);
    }

edit2:我正在考虑这个解决方案,但这似乎不起作用:

public function toArray($request)
{
    return [
        if($this->person == 'nurse') {
            'nurse' => [
                'name' => $this->name,
                'text' => $this->text                   
            ]
        }
        if($this->person == 'physician') {
            'physician' => [
                'name' => $this->name,
                'text' => $this->text                   
            ]
        }
    ];
}

2 个答案:

答案 0 :(得分:0)

$result = YourModel:groupBy('person')->get();
dd($result);

//在模型中定义您的字段名称

答案 1 :(得分:0)

在收集时使用groupBy()

public function index()
{
    $peoples = People::select(['name', 'text', 'person'])->orderBy('id','asc')->get();

    return $peoples->groupBy('person')->toArray();
}