【问题标题】:laravel APi resource Call to undefined method Illuminate\Database\Query\Builder::mapInto()laravel APi 资源调用未定义的方法 Illuminate\Database\Query\Builder::mapInto()
【发布时间】:2018-05-22 11:45:13
【问题描述】:

我有一对一关系的 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
   ];
}
}

任何想法我哪里错了?

【问题讨论】:

    标签: laravel api laravel-5.5


    【解决方案1】:

    问题是您使用UserResource::collection($this-&gt;user),而您只有一个元素而不是集合,因此您可以将其替换为new UserResource($this-&gt;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,
    ];
    

    【讨论】:

    【解决方案2】:

    这个问题是你使用 UserResource::collection($this->user) 这意味着你有很多用户但是你只有一个元素而不是集合所以你可以用 new UserResource($this->user )

    【讨论】:

    • 谢谢,这个回答对我帮助很大。
    【解决方案3】:

    在 Laravel 8.5.* 中,您可以在集合上使用静态方法 make 来获得相同的结果。就像UserResource::make($this-&gt;user)

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 2021-10-18
      • 2018-10-03
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-23
      • 2014-04-25
      • 2017-02-20
      相关资源
      最近更新 更多