You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过关联模型查询关注user_id=1且姓名匹配$_POST['search']的用户?

使用关联模型实现目标用户搜索方案

没问题,我来帮你搞定这个需求!首先得理清楚两张表的关联逻辑:followers表的follower_id是关注者的用户ID,user_id是被关注者的用户ID。我们要找的是所有在followers表中user_id=1对应的follower_id关联的users记录,同时这些用户的name/lastname要匹配你的搜索关键词。

下面以Laravel Eloquent(最常用的关联模型实现)为例,一步步拆解实现:

1. 定义模型关联

1.1 Follower 模型关联

给Follower模型定义两个关联,分别指向「关注者」和「被关注者」:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Follower extends Model
{
    protected $table = 'followers'; // 模型名和表名不一致时需指定

    // 关联到关注者(follower_id 对应 users.id)
    public function follower(): BelongsTo
    {
        return $this->belongsTo(User::class, 'follower_id');
    }

    // 关联到被关注者(user_id 对应 users.id)
    public function followedUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

1.2 User 模型关联

在User模型中定义一个直接关联,方便快速获取「关注当前用户的人」:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;

class User extends Model
{
    // 直接关联到所有关注当前用户的用户(跳过中间Follower模型)
    public function followerUsers(): HasManyThrough
    {
        return $this->hasManyThrough(
            User::class,
            Follower::class,
            'user_id',       // Follower表中关联当前用户的字段
            'id',            // 目标User表的主键
            'id',            // 当前User表的主键
            'follower_id'    // Follower表中关联目标用户的字段
        );
    }
}

2. 编写搜索查询逻辑

现在可以直接通过User模型完成复合条件查询:

// 获取搜索关键词(建议用框架请求类获取,避免直接用$_POST)
$searchTerm = $_POST['search'];

// 查询满足条件的用户
$targetUsers = User::query()
    // 筛选:该用户关注了user_id=1
    ->whereHas('followerUsers', function ($query) {
        $query->where('id', 1);
    })
    // 筛选:name或lastname匹配搜索关键词(支持模糊匹配)
    ->where(function ($query) use ($searchTerm) {
        $query->where('name', 'like', "%{$searchTerm}%")
              ->orWhere('lastname', 'like', "%{$searchTerm}%");
    })
    ->get();

关键代码解释

  • whereHas('followerUsers', ...):用来筛选存在指定关联记录的用户,这里就是找出所有关注了user_id=1的用户。
  • 内层的where(function ($query) ...):把name和lastname的匹配条件分组,确保是「name匹配 或 lastname匹配」,同时结合前面的关注条件。
  • 如果需要精确匹配,把like改成直接相等即可:where('name', $searchTerm)。

3. 安全提示

直接使用$_POST['search']存在SQL注入风险,建议用框架的请求处理方法获取参数,比如Laravel中用request()->input('search'),它会自动处理参数绑定,避免注入问题。

内容的提问来源于stack exchange,提问作者Valter Sousa Cardoso

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:00:27