如何在Laravel控制器中实现多表联查的条件搜索?

我需要在Laravel控制器中完成3张(多张)数据表的联查搜索功能:当用户输入的内容包含演讲者姓名时,展示对应演讲者;同时当输入内容匹配某演讲者关联的topicname时,也需展示该演讲者。
我目前尝试编写的代码如下:
$speaker = Speaker::where ('name','like','%'.$search.'%')->orWhere ........
请问后续的andWhere子句应该如何编写?
实现方法
前置准备
先在Speaker模型中配置好与Topic表的关联关系,以多对多关联为例:
// app/Models/Speaker.php public function topics() { return $this->belongsToMany(Topic::class); }
查询逻辑说明
拼接条件时需要注意两个核心问题,避免查询逻辑出错:
- 所有和搜索相关的匹配条件要放在同一个闭包分组中,防止
orWhere打断全局查询的逻辑优先级 - 关联表的字段匹配优先使用Laravel内置的
whereHas实现,不需要手动编写联表关联条件,减少重复代码
可直接复用的查询代码
$search = trim($request->input('search', '')); if (empty($search)) { // 无搜索词时的兜底逻辑 $speakers = Speaker::with('topics')->get(); } else { $speakers = Speaker::query() ->with('topics') ->where(function ($query) use ($search) { // 匹配演讲者姓名的条件 $query->where('name', 'like', "%{$search}%") // 匹配关联Topic表的topicname字段 ->orWhereHas('topics', function ($topicQuery) use ($search) { $topicQuery->where('topicname', 'like', "%{$search}%"); }); }) ->get(); }
如果需要手动编写联表查询,可参考以下写法,记得去重避免关联带来的重复记录:
$search = trim($request->input('search', '')); $speakers = Speaker::query() ->leftJoin('speaker_topic', 'speakers.id', '=', 'speaker_topic.speaker_id') ->leftJoin('topics', 'speaker_topic.topic_id', '=', 'topics.id') ->where(function ($query) use ($search) { $query->where('speakers.name', 'like', "%{$search}%") ->orWhere('topics.topicname', 'like', "%{$search}%"); }) ->select('speakers.*') ->distinct() ->get();
内容的提问来源于stack exchange,提问作者Tugasprojektengah carispeaker
相关产品推荐
相关产品推荐

