代码之家  ›  专栏  ›  技术社区  ›  gileneusz

laravel条件api资源元素

  •  0
  • gileneusz  · 技术社区  · 6 年前

    我想让你回来 region 通过我的laravel api资源。 区域 是与其他表的关系,因此我通过以下方式访问它:

    return [
       'region' => ['name' => $this->region->name, 'type' => $this->region->type],
    ];
    

    在区域值不为空之前,这是有效的。如果区域值为NULL——它给了我一个错误——不能以未定义的名称命名,所以我试图通过简单地阻止它发生:

       'region' => $this->when($this->region, function(){    
          return ['name' => $this->region->name, 'type' => $this->region->type];
        }),
    

    但问题是-什么时候 区域 表中的值为 NULL -它不提供“区域”空数组作为结果-我需要在前端,所以我试着这样做:

                'region' => $this->when($this->region, function(){
                    return ['name' => $this->region->name, 'type' => $this->region->type];
                }),
                'region' => $this->when(!$this->region, function(){
                    return ['name' => '', 'type' => ''];
                }),
    

    但这不起作用-结果中没有空区域数组:/

    我是做错什么了,还是虫子?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jose Palazuelos    6 年前

    这比您想象的要简单,您可以对空对象使用可选的helper对象

    return [
       'region' => [
           'name' => optional($this->region)->name, 
           'type' => optional($this->region)->type
        ],
    ];
    

    Laravel Method Optional Docs