我有notifications
表的这个模型:
class Notification extends Model
{
public function users()
{
return $this->belongsToMany(User::class, 'notification_user', 'notification_id', 'user_id');
}
}
控制器中的此方法用于从notifications
获取notifications
的id与notification_user
的数据透视表相关的数据:
$myNotifications = DB::table('notification_user')
->join('notifications', 'notifications.id', 'notification_user.notification_id')
->where('notification_user.user_id', $userId)
->where('notification_user.seen', 0)
->get();
$myNotifications
的结果是正确的,但我想使用Model
及其关系而不是DB
。
如何在notifications
中获取每个通知与用户未看到的特定用户相关的所有记录。
答案 0 :(得分:0)
您必须在用户模型中定义与notifications
相同的关系,然后:
$notifications = User::where('id', $user_id)->notifications()->where('seen', 0)->get();
答案 1 :(得分:0)
您需要在关系中添加->withPivot('seen')
:
public function users()
{
return $this
->belongsToMany(User::class, 'notification_user', 'notification_id', 'user_id')
->withPivot('seen');
}
然后你可以这样做:
Notification::whereHas('users', function ($q) use ($userId) {
$q->where('id', $userId)->where('seen', 0);
})->get();
为避免加入用户,您的其他选项为whereExists:
Notification::whereExists(function ($q) use ($userId) {
$q
->selectRaw(1)
->table('notification_user')
->whereRaw('notifications.id = notification_user.notification_id')
->where('user_id', $userId)
->where('seen', 0);
})->get();
仍然应该更高效,但不会更优雅。
答案 2 :(得分:0)
您可以使用with keyword在控制器内进行预先加载。 就像你在模型中定义了任何关系一样,只需在eloquent中的get()语句之前添加一个with(' modelRelation')。
快乐编码。