【发布时间】:2018-03-29 06:38:36
【问题描述】:
我正在尝试使用 Laravel's API Resources 处理一些 JSON,但我无法有条件地加载关系,尽管它已被急切加载。
我的控制器:
$games = Game::with('availableInterests')->get();
在我看来,我正在对要在 VueJS 中使用的集合进行 json 编码
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);
}
}
游戏资源
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() 也不会使这种关系出现。
【问题讨论】:
-
@scipilot 我不这么认为,因为我已经在使用
with()来急切地加载关系 -
你为
Interest创建了资源类吗?在我的 API 应用中对我有用的是'reviews' => ReviewResource::collection($this->whenLoaded('reviews'))。 -
您是否收到错误消息?正如@ashraj98 所说,“available_interests”需要成为一种资源。看起来你正在使用 eloquent 模型
-
尝试强制在你的模型中进行预加载
$with = ['availableInterests'];
标签: laravel