所以,这个问题有点复杂,我什至不知道我是否在正确的解决方案上。
我在数据库中有几个表,我想将它们用作 api。我为一个表创建了一个资源,它返回来自不同表的字段。
我有以下文件:
- Http/Table.php(模型)
- Http/Resources/TableResource.php(资源)
- Http/Controller/Tablecontroller.php( Controller )
- routes/api.php(路由文件)
表格的资源文件如下所示:
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),
}
如您所见,资源引用了不同的资源并为其创建了一个对象。
我的 Controller 有两个功能,可以为所有数据和具有特定 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');
到此为止一切正常。
现在是以下场景:我希望表中的数据不仅按 id 过滤,而且按引用表之一的名称过滤。所以基本上我想要类别->名称为“测试”的所有条目。
我的方法甚至可以做到这一点吗?
最佳答案
如果 TableApi
是您的模型并且您声明了与 Category
模型的关系,您可以执行如下操作:
TableApi::where('id', $id)->whereHas('categories', function($query) {
$query->where('category.name', 'Test')
})->first();
您可以使用 with()
包含相关的 Category
和 Photo
模型。
TableApi::where('id', $id)->whereHas('categories', function($query) {
$query->where('category.name', 'Test')
})->with(['categories', 'photos'])->first();
您可以阅读更多关于 querying relationships existence in the Laravel documentation 的信息.
关于php - Laravel 资源 api 使用引用表的 where 子句获取所有条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225838/