怎么优雅的多字段搜索

$topic = QueryBuilder::for(Topic::class)
            ->allowedIncludes('category', 'user')
            ->allowedFilters([
                'title',
                'auto_title',
                'body',
                AllowedFilter::exact('category_id'),
                AllowedFilter::scope('withOrder')->default('recentReplied'),
            ])
            ->paginate(10);

这样的话,就是如下的链接请求

topics?include=user&page=1&filter[category_id]=&filter[title]=关键词&filter[auto_title]=关键词&filter[body]=关键词

这样的搜索就是,要么3个字段都满足才会有结果,要么只能搜索单一字段,怎么优化一下可以3个字段同时搜索呢?

=================

比如像下面这样就可以搜索多字段:

topics?include=user&page=1&filter[category_id]=&filter[keyword]=关键词
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 5

拆分一下, 有条件的搜索 $array=compact ('category_id','status','user_id'); // 生成之后需要过滤一下非空 -字段名和数据表中的字段要搜索的字段对应 模糊搜索 最后合并 $query->whereRaw ("(concat (' 字段 1',' 字段 2',' 字段 3') like '%" . $keywords . "%')")->where ($array);

1年前 评论
chowjiawei

不太理解需求

1年前 评论

是这样的吗

...
AllowedFilter::callback('keyword', function (Builder $query, $value){
    $query
        ->where('title', 'like', "$value%")
        ->orWhere('auto_title', 'like', "$value%")
        ->orWhere('body', 'like', "$value%");
}),
...
1年前 评论

推荐一个我比较喜欢用的检索扩展,采用查询作用域扩展的 github.com/Tucker-Eric/EloquentFil...

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!