我有一对一的帖子和用户模型,效果很好:

//User.php

public function post(){
    return $this->hasOne(Post::class);
}


// Post.php

public function user() {
    return $this->belongsTo(User::class);
}

现在我创建API资源:

php artisan make:resource Post
php artisan make:resource User

I need to return all post with an api call then i set my route:

//web.php: /resource/posts

Route::get('/resource/posts', function () {
    return PostResource::collection(Post::all());
});

这是我的帖子资源课:

<?php

namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
use App\Http\Resources\User as UserResource;

class Posts extends Resource
{
/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
      return [
        'id' => $this->id,
        'title' => $this->title,
        'slug' => $this->slug,
        'bodys' => $this->body,
        'users' => UserResource::collection($this->user),
        'published' => $this->published,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];

}
}

this is the error:

Call to undefined method Illuminate\Database\Query\Builder::mapInto()

如果我删除:

'users' => UserResource::collection($this->user),

这是工作,但我需要在我的API json中包括关系,我已经阅读并关注了https://laravel.com/docs/5.5/collections岁的文档.

这是我的用户资源类:

```

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\Resource;

class User extends Resource
{
/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
   return [
       'user_id' => $this->user_id,
       'name' => $this->name,
       'lastname' => $this->lastname,
       'email' => $this->email
   ];
}
}

any ideas where am i wrong?

推荐答案

The problem is that you use UserResource::collection($this->user) and you have just one element not a collection so you can replace it with new UserResource($this->user) like this :

return [
    'id' => $this->id,
    'title' => $this->title,
    'slug' => $this->slug,
    'bodys' => $this->body,
    'users' => new UserResource($this->user),
    'published' => $this->published,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
];

Laravel相关问答推荐

Laravel使用PostgreSQL显示";`try 读取null`上的属性,而不是SQL错误消息

自定义验证在表单请求上始终返回 true laravel

Laravel 通过 API 嵌套 url 发布

Livewire 基于下拉 Select 自动填充输入框

Vue 组件中的图像不适用于 Vite + Laravel

当两个外键都在同一个表上时创建直通关系

模型文件名更改数据库中的表名

使用 laravel 根据当月显示注册用户列表

不能在 laravel 中使用控制器名称,必须使用命名空间

Blade引擎:打印三重花括号

Laravel 5表单请求验证返回禁止错误

Laravel 没有定义

如何判断是否在laravel中设置了cookie?

Laravel 5 文件下载:stream() 或 download()

计算laravel中查询返回的行数

如何访问 Carbon 对象类型?

Laravel 5 干预中的图像验证

使用 Laravel 将两个模型合并到一个分页查询中,并带有Eager加载的关系

未找到列:1054 未知列 laravel

找不到框laravel/homestead