我在实施Fractal包含时遇到问题。我正在尝试包含特定用户的帖子。
当我将“帖子”添加到我的UserItemTransformer顶部的 $ defaultIncludes 时,一切顺利。帖子按预期包含在内。
但是,即使在调用$fractal->parseIncludes('posts');
问题似乎在于,只有当我使用$ 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');
答案 0 :(得分:2)
知道了!
当我调用parseIncludes(' posts')时,这是一个新的Fractal实例,注入到控制器方法中。当然我应该在Fractal实例上调用parseIncludes(),它实际解析(并且我将其他地方注入到Api类中)。
public function postsWithUser($user_id, Manager $fractal, UserRepositoryInterface $userRepository)
{
$api = new \App\Services\Api();
$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());
}
我现在只是坐在一个角落,现在真的退出了一段时间。