laravel-更改API资源数组中的值

时间:2018-09-25 10:52:47

标签: laravel

{
"data": {
   "username": "candy",
   "certificates": [
   {
   "id": 11,
   "category_id": 1,
   "certname": "cert name test",
   "created_at": "2018-08-18 00:58:12",
   "updated_at": "2018-08-18 00:58:12"
   }
   ]
 }
}

以上是使用Eloquent:API资源的响应。

我想输入类别名称而不是category_id。

下面是资源类

    public function toArray($request)
{
    return [
        'nickname' => $this->nickname,
        'certificates' => $this->certificates,
    ];
}

证书位于数组中(具有许多关系)

证书属于类别

3 个答案:

答案 0 :(得分:0)

这可能会有所帮助, 运行foreach循环

$category = "Your SELECT Query";
foreach ($category as $value) {
               $categoryId = json_decode($value->category_id);
               $x = Category::select('certname')->whereIn('id', $categoryId)->get();
               foreach ($x as $as) {
                   $y[] = $as->certname;
               }
               $value->certname = $y;

答案 1 :(得分:0)

在这种情况下,您可以在资源类中获取每个证书的类别名称并将其附加。

public function toArray($request)
{

    $certificateList = $this->certificates;

    foreach($certificateList as $ceritificate) {

         // fetch only the category name from the database.
         // attach to the certificate.

         $categoryName = Category::where('id', $certificate->category_id)->pluck('name')->first();
         $certificate->setAttribute('category_name, $categoryName);
    }

    // then as usual
    return [
         'nick_name' => $this->nick_name,
         'certificates' => $certificateList
    ];
}

答案 2 :(得分:0)

您可以这样做

在控制器中

 return    CertificateResource::collection(Certificate::with('category')->get());

在CertificateResource中

 return [
    'nickname' => $this->nickname,
    'certificates' => $this->certificates,
    'category_name'=>$this->whenLoaded('category', function () {
            return $this->category->category_name;
        }),
];