我希望用户对Model条目进行排序和过滤,在我的laravel后端中,我有一个搜索方法API调用,目前我无法让Scout的Model :: search方法与Eloquent的查询生成器一起使用,因此您可以:
1)按文字搜索 2)雄辩地排序或过滤。
我的搜索方法:
public function search(Request $request, QueryFilters $filters)
{
if($request->has('search'))
{
$posts = Post::search($request->input('search'))->paginate(10);
$posts->load(['postcategory','author','favorites']);
if($posts->isEmpty())
{
return response()->json([
'message' => 'No se encontraron resultados',
],500);
}
return response()->json([
'message' => 'Encontramos unas coincidencias',
'posts' => $posts,
], 200);
}
else
{
$posts = Post::filter($filters)->with(['postcategory','author','favorites'])->paginate(10);
if($posts->isEmpty())
{
return response()->json([
'message' => 'No se encontraron resultados',
],500);
}
return response()->json([
'message' => 'Encontramos unas coincidencias',
'posts' => $posts,
], 200);
}
}
如果您想知道Model :: filter是做什么的,它只是遍历请求查询参数并使用Eloquent进行排序和过滤,您可以查看这篇中等文章:
https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8
<?php
namespace App\Filters;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class QueryFilters
{
protected $request;
protected $builder;
public function __construct(Request $request)
{
$this->request = $request;
}
public function title($term)
{
$lowerCaseTerm = strtolower($term);
return $this->builder->where('title', 'LIKE', "%$lowerCaseTerm%");
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach ($this->filters() as $name => $value)
{
//if method doesn't exists continue out of the loop
if ( ! method_exists($this, $name))
{
continue;
}
//method exists so check if it has a value payload so call the method with arguments
if (strlen($value))
{
$this->$name($value);
}
//it doesn't have a payload so call the method without arguments
else
{
$this->$name();
}
}
return $this->builder;
}
public function filters()
{
//returns associative array of request body key value pairs
return $this->request->all();
}
}