Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel资源-从关系中获取数据_Php_Laravel - Fatal编程技术网

Php Laravel资源-从关系中获取数据

Php Laravel资源-从关系中获取数据,php,laravel,Php,Laravel,我正在尝试使用Laravel的资源和集合来构建一个小型API 我想恢复所有类别的职位 我的模型上的关系: /* |-------------------------------------------------------------------------- | RELATIONS |-------------------------------------------------------------------------- */ public function posts() {

我正在尝试使用Laravel的资源和集合来构建一个小型API

我想恢复所有类别的职位

我的模型上的关系:

/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function posts()
{
    return $this->belongsToMany(Post::class, 'post_category');
}
类别控制员:

public function index()
{
    $categories = Category::all();

    return (new CategoryCollection(CategoryResource::collection($categories)));
}
我的类别资源:

public function toArray($request)
{
    return [
        'id'   => $this->id,
        'name' => $this->name,
        'slug' => $this->slug
    ];
}
我的分类集合

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'posts' => PostResource::collection($this->whenLoaded('posts')),
    ];
}
我尝试先恢复某个类别的帖子。当我发出以下命令时,我得到一个错误:方法。。。relationLoaded不存在

'posts'=>PostResource::collection($this->whenLoaded('posts'))

我不明白什么

我还创建了两个PostCollection和PostResource文件(基本,我没有修改它们)

这可能会有帮助,试试这个

如果你想使用posts资源 你需要制造资源 在分类资源中

'posts'=>PostResource::collection($this->posts)

无法在集合中使用资源。 用这个

public function index()

{
    $categories = Category::all();

    return (CategoryResource::collection($categories));
}
'posts'=>PostResource::collection($this->posts)
public function index()
{
    $categories = Category::all();

    return (new CategoryCollection($categories));
}