Laravel 5.8 PHP 7.4
我想有条件地加载关系
http://127.0.0.1:8000/api/posts
和
http://127.0.0.1:8000/api/posts/1 are my end points now, I want to load comments like
http://127.0.0.1:8000/api/posts/?include=comments
和
http://127.0.0.1:8000/api/posts/1/?include=comments
如果查询参数在那里,那么它应该加载带有帖子的评论,或者它应该只加载帖子/帖子
我通过参考博客文章来做到这一点
现在,RequestQueryFilter
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
class RequestQueryFilter
{
public function attach($resource, Request $request = null)
{
$request = $request ?? request();
return tap($resource, function($resource) use($request) {
$this->getRequestIncludes($request)->each(function($include) use($resource) {
$resource->load($include);
});
});
}
protected function getRequestIncludes(Request $request)
{
// return collect(data_get($request->input(), 'include', [])); //single relationship
return collect(array_map('trim', explode(',', data_get($request->input(), 'include', [])))); //multiple relationships
}
}
并在助手中
<?php
if ( ! function_exists('filter') ) {
function filter($attach)
{
return app('filter')->attach($attach);
}
}
?>
在 PostController
public funciton show(Request $request, Post $post) {
return new PostResource(filter($post));
}
但是当我试图检索
http://127.0.0.1:8000/api/posts/1/?include=comments getting no comments, with no error in log
解决方法是 PostResource
public function toArray($request)
{
// return parent::toArray($request);
$data = [
'id' => $this->id,
'name' => $this->title,
'body' => $this->content,
];
$filter = $request->query->get('include', '');
if($filter){
$data[$filter] = $this->resource->$filter;
}
return $data;
}