嗨,我正在开发一个用于检索分页用户列表的 rest api 端点。在前端,可以选择搜索所有列出的列、按所有列排序并按名称、状态和创建日期过滤。
到目前为止,我已经在用户模型中创建了一个存储库和本地范围,用于搜索、排序和过滤。到目前为止,这是我的代码。我对过滤器选项感到困惑。由于用户具有所有三个选项的调用过滤器。如何以最优化的方式在 api 中传递这些值?
Controller :
public function index(Request $request)
{
$this->userRepository->getAllUsers($request);
}
存储库函数:
public function getAllUsers($request)
{
// Search Parameter
isset($request->q)? $q = $request->q: $q = null;
// Sort Parameter
if ( isset($request->sortby) && (isset($request->direction)) ) {
$sort[$request->sortby] = $request-> direction;
}
return User::where('type','=','student')
->ofSearch($q)
->ofSort($sort)
->paginate($per_page)
}
型号:
public function scopeOfSearch($query, $q)
{
if ( $q ) {
$query->orWhere('name', 'LIKE', '%' . $q . '%')
->orWhere('school', 'LIKE', '%' . $q . '%')
->orWhere('email', 'LIKE', '%' . $q . '%')
->orWhere('phone', 'LIKE', '%' . $q . '%')
->orWhere('class', 'LIKE', '%' . $q . '%');
}
return $query;
}
public function scopeOfSort($query, $sort = [])
{
if ( ! empty($sort) ) {
foreach ( $sort as $column => $direction ) {
$query->orderBy($column, $direction);
}
}
else {
$query->orderBy('users.name');
}
return $query;
}
最佳答案
无论如何,我修复了它,我创建了另一个 post 端点,它将发送所有过滤器及其值。我不确定这是否是正确的方法,但现在我只能这样想。
更新
我已经按照以下教程实现了过滤器。
https://m.dotdev.co/writing-advanced-eloquent-search-query-filters-de8b6c2598db
关于Laravel 5.6 Api - 搜索、排序和过滤数据列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51555959/