Laravel 如何在Api资源中以相同的名称返回不同的关系

Laravel 如何在Api资源中以相同的名称返回不同的关系,laravel,api,laravel-5,laravel-5.6,Laravel,Api,Laravel 5,Laravel 5.6,在我的项目中,我建立了多种关系,如: 型号 public function foo() { return $this->hasMany(Bar::class); } public function fooSold() { return $this->hasMany(Bar::class)->where('sold', 1); } 控制器 public function show() { $bar = Bar::with('foo')->first(

在我的项目中,我建立了多种关系,如:

型号

public function foo() 
{ 
  return $this->hasMany(Bar::class);
}

public function fooSold() 
{ 
  return $this->hasMany(Bar::class)->where('sold', 1);
}
控制器

public function show()
{
  $bar = Bar::with('foo')->first();
  return new BarResource($bar);
}

public function showSold()
{
  $bar = Bar::with('fooSold')->first();
  return new BarResource($bar);
}
资源

public function toArray($request)
return [
...
'foo' => Foo::collection($this->whenLoaded('foo')),
]
返回控制器中的第一个函数没有任何问题。但是,如何在我的资源中以与“foo”相同的名称返回第二个呢

'foo' => Foo::collection($this->whenLoaded'fooSold')),
'foo' => Foo::collection($this->whenLoaded'foo')),
这是可行的,但似乎不是正确的方法,因为您有两次相同的数组键


执行此操作的最佳方法是什么?

数组的全部要点是具有唯一的键。如果要存储成对的值,请创建一个数组,如:

$array[] = [$value1, $value2];
在您的情况下,类似于:

'foo' => [Foo::collection($this->whenLoaded'fooSold')), Foo::collection($this->whenLoaded'foo'))]
对于第二种情况,请使用a:

public function scopeSold($query) 
{ 
    return $query->whereHas('foo', function ($q) { 
        $q->where('sold', 1);
    });
}

// call the scope
$sold = Foo::sold();
试试这个:

'foo' => Foo::collection($this->whenLoaded('foo') instanceof MissingValue ? $this->whenLoaded('fooSold') : $this->whenLoaded('foo')),

这确实是一种可能性,但我必须重写前端的一部分,因为它返回的是封装在数组中的。因此,我选择了DigitalDriver的答案,但事实并非如此。