Laravel 资源 api 以获取带有引用 table 的 where 子句的所有条目

Laravel resource api to get all entries with where clause of referenced table

所以,这个问题有点复杂,我不知道我是否在正确的解决方案上了。
我在数据库中有几个 table,我想将其用作 api。我为 table 创建了一个资源,其中 returns 字段来自不同的 table。

我有以下文件:

table 的资源文件如下所示:

public function toArray($request)
{
    'id' => $this->id,
    'created_at' => $this->created_at,
    'updated_at' => $this->updated_at,
    'name' => $this->name,
    'website' => $this->website,
    'categories' => CategoryResource::collection($this->categories),
    'photos' => PhotoResource::collection($this->photos),
}

如您所见,该资源引用了不同的资源并为其创建了一个对象。
我的控制器有两个功能,可以为所有数据和具有特定 ID 的数据提供服务。

看起来像这样:

public function showAll()
{
    return TableResource::collection(TableApi::all());
}

public function show($id)
{
    return new TableResource(TableApi::find($id));
}

最后我做了一些路线:

Route::get('/table', 'TableController@showAll');
Route::get('/table/{id}', 'TableController@show');

在此之前一切正常。
现在是以下场景:我希望来自 table 的数据不仅按 ID 过滤,而且按引用的 table 之一的名称过滤。所以基本上我想要类别->名称为 "Test".
的所有条目 这甚至可以用我的方法吗?

如果 TableApi 是您的模型并且您声明了与 Category 模型的关系,您可以执行以下操作:

TableApi::where('id', $id)->whereHas('categories', function($query) {
    $query->where('category.name', 'Test')
})->first();

您可以使用 with().

包含相关的 CategoryPhoto 模型
TableApi::where('id', $id)->whereHas('categories', function($query) {
    $query->where('category.name', 'Test')
})->with(['categories', 'photos'])->first();

您可以阅读有关 querying relationships existence in the Laravel documentation 的更多信息。