如何 return 不同的关系作为 Api 资源中的同名
How to return different relation as the same name in an Api Resource
在我的项目中,我设置了多个关系,例如:
型号
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')),
]
在我的控制器中返回第一个函数没有任何问题。但是我如何 return 第二个与我的资源中的 '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'))]
第二种情况使用local query scope:
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')),
在我的项目中,我设置了多个关系,例如:
型号
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')),
]
在我的控制器中返回第一个函数没有任何问题。但是我如何 return 第二个与我的资源中的 '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'))]
第二种情况使用local query scope:
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')),