You need to enable JavaScript to run this app. 如何在Laravel控制器中实现多表联查的条件搜索?
优惠活动
大模型
产品
解决方案
定价
更多

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

table

我需要在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 21:54:10