资源:将PivotLoaded作为条件时使用

时间:2019-10-05 10:19:16

标签: laravel eloquent laravel-collection laravel-eloquent-resource

我想要这个:

  • 集合在没有数据透视表的情况下返回var imagesList =new ListVWidgetC(); for(int i=0;iVimagesClength;i++) { imagesListCadd( CircleAvatar ( ghackgroundImage: AssetImage(imgUrl)); }
  • 集合在加载数据透视后返回'title' => $this->title

这是我的方法:

title => $this->pivot->title . "Hello World"

如果我尝试这样的事情:

namespace App\Http\Resources;

use App\Item;
use Illuminate\Http\Resources\Json\JsonResource;


class ItemResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {

        return [
            'id'     => $this->id,
            'title'  => $this->whenPivotLoaded('item_groups_attribute',
                function () {
                    return $this->pivot->title . "Hello";
                }), // but how to add $this->title, if it's not with pivot?
        ];
    }
}

这不起作用,因为结果是

无中心点(标题不会显示在字段中)

'title'  => $this->whenPivotLoaded('item_groups_attribute',
                function () {
                    return $this->pivot->title . "Hello";
                }) ?: $this->title,

这是如果使用数据透视加载的响应:

{
  "data": {
    "id": 2
  }
}

1 个答案:

答案 0 :(得分:0)

由于数据透视表已加载或未加载,只需对整个表达式取反来替换另一个字段,就永远不会重复

public function toArray($request)
{

    return [
        'id'     => $this->id,
        'title'  => $this->whenPivotLoaded('item_groups_attribute',
            function () {
                return $this->pivot->title . "Hello";
            }),
        'title'  => !$this->whenPivotLoaded('item_groups_attribute',
            function () {
                return $this->title;
            }),
    ];
}