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

Laravel:如何从关联中间表的通知表中获取数据

获取当前用户的关联通知数据(Laravel)

你已经定义了Notification模型和User的多对多关联,其实有两种优雅的方式来实现需求,我帮你分别整理:

方法一:利用Eloquent关联(推荐)

既然已经在Notification里定义了users()关联,建议先在User模型中补充反向关联(如果还没加的话):

class User extends Model {
    // 其他代码...
    public function notifications() {
        return $this->belongsToMany(Notification::class, 'notification_user', 'user_id', 'notification_id');
    }
}

然后在控制器里,直接通过当前用户的关联关系获取通知,代码非常简洁:

// 获取当前用户的所有通知
$myNotifications = auth()->user()->notifications()->get();

// 如果需要筛选特定条件(比如未读通知),直接追加where即可
$myNotifications = auth()->user()->notifications()
    ->where('is_read', false)
    ->orderBy('created_at', 'desc')
    ->get();

这种方式完全贴合Laravel的ORM设计,代码可读性高,还能自动利用模型的各种特性(比如访问器、事件)。

方法二:完善你的查询构造器代码

如果你坚持用DB查询构造器的方式,需要补全where条件、修正join语法,并指定要查询的字段:

$userId = auth()->id(); // 获取当前登录用户的ID

$myNotifications = DB::table('notification_user')
    ->join('notifications', 'notifications.id', '=', 'notification_user.notification_id') // 注意这里要加=
    ->where('notification_user.user_id', $userId) // 筛选当前用户的关联记录
    ->select('notifications.*') // 只取notifications表的所有字段,避免字段冲突
    // 可选:添加排序或其他筛选
    ->orderBy('notifications.created_at', 'desc')
    ->get();

这里要注意join条件必须包含=,否则会报错;另外通过select指定字段可以避免中间表和通知表的同名字段(比如created_at)冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:42:09