我应该如何用Lumen的Laravel API资源替换hasMany()关系



我正在将Laravel 5.7应用程序迁移到Lumen,同时引入Laravel API资源

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

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

public function tournaments()
{
return $this->hasMany('AppTournament');
}

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

我有:

class TournamentResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param  IlluminateHttpRequest $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()
];
}
}

有什么想法吗?

neneneba API资源只是格式化返回数据的方式。它不会影响你们的关系。您唯一需要做的就是将对象/集合(取决于情况)传递给API Resource类。

资源集合

如果返回资源集合或分页响应,则可以在以下情况下使用collection方法在路由或控制器中创建资源实例:

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

如您所见,只需使用它:

TournamentsController.php

use AppHttpResourcesTournamentResource;
//
public function index()
{
$tournaments = auth()->user()->tournaments;
return TournamentResource::collection($tournaments);
}

请查看有关此方面的文档。此外,要加载子项(championship),您可以热切地加载/懒惰地热切地加载关系项。


观察:

在关系中,当你像方法(auth()->user()->tournaments())一样使用它时,你就是在访问关系本身,当你想继续约束关系时,请使用full。当您将其用作属性(auth()->user->tournaments)时,您正在访问查询的结果。

请检查此答案以获得更好的解释。

如果您从Laravel迁移到Lumen,首先需要确保您在app/bootstrap.php文件中启用了雄辩。

请遵循本指南以确保您遵循相同的指南。一旦遵循了这些规则,上面的代码就应该可以工作了。

最新更新