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

Laravel中如何通过JSON字段userid关联comment与users表?

Laravel JSON字段关联查询修正方案

你的代码存在几个关键问题,以下是修正后的写法及错误说明:

错误点说明

  • JOIN条件无效:原代码中join("users", "users.id", "=", "users.id")是无意义的自关联,没有建立comment表和users表的有效关联逻辑
  • 语法错误:闭包调用前缺少方法名,且存在多余的->符号
  • JSON查询参数错误:whereJsonContains中直接写users.id会被Laravel当作字符串处理,而非数据库列名

正确查询写法(基于JOIN)

根据你的tags字段JSON结构,分两种场景处理:

场景1:tags是包含userid的对象数组(如[{"userid":1}, {"userid":2}])

use Illuminate\Support\Facades\DB;

$messages = TopicComment::where('user_id', $currentUserId)
    ->join('users', function ($join) {
        $join->whereJsonContains('topic_comments.tags', ['userid' => DB::raw('users.id')]);
    })
    ->get()
    ->toArray();

场景2:tags是嵌套的userid数组(如{"userid": [1,2,3]})

use Illuminate\Support\Facades\DB;

$messages = TopicComment::where('user_id', $currentUserId)
    ->join('users', function ($join) {
        $join->whereJsonContains('topic_comments.tags->userid', DB::raw('users.id'));
    })
    ->get()
    ->toArray();

可选方案:Eloquent关联简化查询

如果希望用Eloquent关联简化代码,可在TopicComment模型中定义关联方法:

// app/Models/TopicComment.php
use App\Models\User;
use Illuminate\Support\Facades\DB;

public function taggedUsers()
{
    return $this->belongsToMany(User::class, 'topic_comments', null, 'id', null, 'id')
        ->whereJsonContains('topic_comments.tags->userid', DB::raw('users.id'));
}

之后查询时直接调用关联:

$messages = TopicComment::where('user_id', $currentUserId)
    ->with('taggedUsers')
    ->get()
    ->toArray();

内容的提问来源于stack exchange,提问作者Nikul Panchal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:16:26