我尝试使用Laravel's API Resources来处理某些JSON,并且我无法有条件地加载关系,尽管它已被迫加载。
我的控制器:
$games = Game::with('availableInterests')->get();
在我看来,我是json编码要在VueJS中使用的集合
games = @json(new \App\Http\Resources\GameCollection($games)),
GameCollection - 与Laravel为我生成的类保持不变。
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\ResourceCollection;
class GameCollection extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
GameResource
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'thumbnail_url' => $this->thumbnail_url,
'available_interests' => Interest::collection($this->whenLoaded('availableInterests')),
];
}
}
游戏模型的关系
public function availableInterests() : BelongsToMany
{
return $this->belongsToMany(Interest::class);
}
我尝试将$this->whenLoaded('availableInterests')
更改为$this->whenLoaded('available_interests')
但没有运气。我没有运气就检查了我的拼写。
为什么这个conditional relationship出现在json中?
即使删除$this->whenLoaded()
也不会显示此关系。
答案 0 :(得分:1)
在这种情况下,我认为你不需要GameCollection。
我会尝试这样做:
InterestResource.php (创建新课程)
class InterestResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
// or what ever array structure you want
}
}
<强> GameResource.php 强>
class GameResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'thumbnail_url' => $this->thumbnail_url,
'available_interests' => InterestResource::collection($this->whenLoaded('availableInterests')),
];
}
}
您的控制器
$games = Game::with('availableInterests')->get();
您的观点
games = @json(\App\Http\Resources\GameResource::collection($games)),