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

Laravel 8 关联action_users等多表查询当前登录用户数据的问题

现有代码存在的问题

  • users表关联逻辑完全错误:join('users', '$user', 'action_users.user_id') 不符合join语法规范,join关联两张表时,第二、三个参数应为两张表的关联字段名,你错误传入了用户ID变量,且单引号包裹导致变量无法解析。
  • 缺少核心筛选条件:没有针对action_users.user_id添加等于当前认证用户ID的where条件,即使关联逻辑修正也会返回所有用户的数据。
  • 冗余的groupBy语句:需求仅为查询当前用户的关联记录,不需要分组逻辑,多余的groupBy还可能在数据库开启严格模式时触发语法报错。

正确实现方案

方案1:修正原生DB查询写法

@php
        $userId = auth()->id();

        $total = DB::table('action_users')
            ->join('users', 'users.id', '=', 'action_users.user_id')
            ->join('actions', 'actions.id', '=', 'action_users.action_id')
            ->where('action_users.user_id', $userId)
            ->select('users.id', 'users.name', 'users.email', 'action_users.point', 'actions.action_title', 'actions.action_image', 'action_users.created_at')
            ->get();

        dd($total);
@endphp

方案2:基于已定义模型关联的Eloquent写法(推荐)

你已经在ActionUser模型中定义了user和action的关联关系,直接使用Eloquent查询可以避免手写join出错,代码更简洁易维护:

@php
        $total = \App\Models\ActionUser::query()
            ->with(['user', 'action'])
            ->where('user_id', auth()->id())
            ->get();

        dd($total);
@endphp

查询结果可以直接通过关联属性访问对应字段,比如$total[0]->user->name获取用户名,$total[0]->action->action_title获取活动标题。如果需要和之前一样的扁平化结构,可以追加map处理:

$total = $total->map(fn($item) => [
    'id' => $item->user->id,
    'name' => $item->user->name,
    'email' => $item->user->email,
    'point' => $item->point,
    'action_title' => $item->action->action_title,
    'action_image' => $item->action->action_image,
    'created_at' => $item->created_at,
]);

内容的提问来源于stack exchange,提问作者ALAA ELDIN

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:18:00