我在实现分形包含时遇到问题。我正在尝试包含特定用户的帖子。
当我在UserItemTransformer的顶部添加"帖子"到$defaultIncludes时,一切都很顺利。帖子按预期包括在内。但是,当我将$defaultIncludes更改为$availableIncludes时,即使在调用$fractal->parseIncludes('posts');
之后,我的 json 输出中也不会包含帖子
问题似乎在于这样一个事实,即包含帖子的方法仅在我使用$defaultIncludes时才调用,当我使用$availableIncludes时永远不会调用。
我可能在这里错过了一些明显的东西。你能帮我找出它是什么吗?
这有效:
// [...] Class UserItemTransformer
protected $defaultIncludes = [
'posts'
];
这不起作用:
// [...] Class UserItemTransformer
protected $availableIncludes = [
'posts'
];
// [...] Class PostsController
// $fractal is injected in the method (Laravel 5 style)
$fractal->parseIncludes('posts');
知道了!
当我调用parseInclude('posts')时,这是在一个新的分形实例上,注入到控制器方法中。当然,我应该在执行实际解析的分形实例上调用parseInclude()(并且我在其他地方注入到Api类中)。
public function postsWithUser($user_id, Manager $fractal, UserRepositoryInterface $userRepository)
{
$api = new AppServicesApi();
$user = $userRepository->findById($user_id);
if ( ! $user) {
return $api->errorNotFound();
}
$params = [
'offset' => $api->getOffset(),
'limit' => $api->getLimit()
];
$user->posts = $this->postRepository->findWithUser($user_id, $params);
// It used to be this, using $fractal, that I injected as method parameter
// I can now also remove the injected Manager $fractal from this method
// $fractal->parseIncludes('posts');
// I created a new getFractal() method on my Api class, that gives me the proper Fractal instance
$api->getFractal()->parseIncludes('posts');
return $api->respondWithItem($user, new UserItemTransformer());
}
我现在就坐在角落里,暂时戒掉