laravel APi资源调用未定义的方法Illuminate \ Database \ Query \ Builder :: mapInto()

时间:2017-12-08 08:59:46

标签: laravel api laravel-5.5

我有一对一关系的Post和User模型,它运作良好:

//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

我需要通过api调用返回所有帖子然后我设置我的路线:

//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,
    ];

}
}

这是错误:

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
   ];
}
}

任何想法我错了吗?

2 个答案:

答案 0 :(得分:37)

问题是您使用的是UserResource::collection($this->user),而您只有一个元素而不是集合,因此您可以将其替换为new UserResource($this->user),如下所示:

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,
];

答案 1 :(得分:0)

此问题是您使用UserResource :: collection($ this-> user)意味着您有很多用户,但是只有一个元素而不是集合,因此可以将其替换为新的UserResource($ this-> user )