我应该如何用 Laravel API Resources for Lumen 替换 hasMany() 关系

How should I replace a hasMany() relationship with Laravel API Resources for Lumen

我正在将 Laravel 5.7 应用迁移到 Lumen,同时引入 Laravel API Resources

在我的旧代码库中,我有:

$tournaments = Auth::user()->tournaments();

public function tournaments()
{
    return $this->hasMany('App\Tournament');
}

但是现在,在 Lumen 中,我使用 API 资源,所以不知道如何获得相同的结果,但是使用提供 API 资源的所有修饰的额外字段。

我有:

class TournamentResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'user' => User::findOrFail(Auth::user()->id)->email,
            'championships' => ChampionshipResource::collection($this->whenLoaded('championships')),
            'competitors_count' => $this->competitors->count()
        ];
    }
}

有什么想法吗?

API 资源只是按照返回数据的方式进行格式化。它不会影响你的人际关系。您唯一需要做的就是将 object/collection(视情况而定)传递给 API 资源 class.

Resource Collections

If you are returning a collection of resources or a paginated response, you may use the collection method when creating the resource instance in your route or controller:

use App\User;
use App\Http\Resources\User as UserResource;

Route::get('/user', function () {
    return UserResource::collection(User::all());
});

如你所见,直接使用即可:

TournamentsController.php

use App\Http\Resources\TournamentResource;

//

    public function index()
    {
        $tournaments = auth()->user()->tournaments;

        return TournamentResource::collection($tournaments);
    }

检查 documentation regarding this aspect. Also, to load the child items (championship), you can Eager Load/Lazy Eager Load 关系项。


观察:

在关系中,当您像使用方法 (auth()->user()->tournaments()) 一样使用它时,您正在访问关系本身,这在您想要继续约束关系时很有用。当您将它用作属性 (auth()->user->tournaments) 时,您正在访问查询结果。

以获得更好的解释。

如果您从 Laravel 迁移到 Lumen,您首先需要确保在 app/bootstrap.[=18= 中启用了 eloquent ] 文件.

请关注 this guide 以确保您关注的是相同的。一旦遵循这些代码,上面的代码应该可以工作。