如何为DatabaseNotification关联获取对应用户数据?
实现DatabaseNotification关联用户的方法
1. 创建自定义通知模型
Laravel默认的DatabaseNotification是框架内置类,建议创建自定义模型继承它,避免修改核心文件:
<?php namespace App\Models; use Illuminate\Notifications\DatabaseNotification; class Notification extends DatabaseNotification { // 定义关联用户的方法 public function user() { // 请根据实际项目调整用户模型的命名空间 return $this->belongsTo(User::class, 'notifiable_id'); } }
2. 关联的约束补充
如果你的通知系统中notifiable_type对应多种模型,但当前仅需关联用户,可以在关联方法中添加约束,确保只关联用户数据:
public function user() { return $this->belongsTo(User::class, 'notifiable_id') ->where('notifiable_type', User::class); }
3. 使用自定义模型查询
现在就能通过with()预加载用户数据:
$notificationList = \App\Models\Notification::where('type','App\Notifications\NewBulletinNotification') ->with('user') ->get(); // 访问用户数据示例 foreach ($notificationList as $notification) { echo $notification->user->name; }
无需自定义模型的替代方案
如果不想创建自定义模型,可直接利用DatabaseNotification自带的morphTo关联,通过闭包过滤用户类型:
$notificationList = \Illuminate\Notifications\DatabaseNotification::where('type','App\Notifications\NewBulletinNotification') ->with(['notifiable' => function ($query) { $query->where('notifiable_type', \App\Models\User::class); }]) ->get(); // 访问用户数据示例 foreach ($notificationList as $notification) { echo $notification->notifiable->name; }
内容的提问来源于stack exchange,提问作者Nicolò Scapin
相关产品推荐
相关产品推荐

