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

Laravel技术问询:如何通过data->postid删除数据库通知行

Delete Laravel Database Notifications by postid in JSON data Field

Got it, let's walk through how to delete those specific database notifications using the postid stored in the JSON data column. Since Laravel handles JSON fields natively in the query builder, this is straightforward once you know the right methods to use.

Method 1: Using Query Builder Directly

You can target the notifications table directly, filtering by the notifiable user, notification type (optional but recommended), and the postid inside the data JSON:

use Illuminate\Support\Facades\DB;
use App\Models\User;

// Define your target values
$targetUserId = 48; // The user who received the notification
$targetPostId = 123; // The post ID from the notification data

DB::table('notifications')
    // Filter by the user who owns the notification
    ->where('notifiable_type', User::class)
    ->where('notifiable_id', $targetUserId)
    // Optional: Only target PostLiked notifications
    ->where('type', 'App\Notifications\PostLiked')
    // Match the postid inside the JSON data field
    ->whereJsonContains('data->postid', $targetPostId)
    ->delete();

Method 2: Using the User Model's Notifications Relationship

If your User model uses the Notifiable trait (which it should, since you're using database notifications), you can use the built-in notifications relationship to make the query more expressive:

use App\Models\User;

$user = User::find(48);

$user->notifications()
    ->where('type', 'App\Notifications\PostLiked')
    ->whereJsonContains('data->postid', 123)
    ->delete();

Key Notes

  • Double-check the key name in your JSON data: Make sure it's exactly postid (case-sensitive!) as shown in your example data. If it's camelCase like postId, adjust the query to data->postId.
  • whereJsonContains works in Laravel 5.5+ (which matches your version), so you don't have to worry about compatibility issues here.
  • If you need to delete notifications for a post across all users (not just one), simply remove the notifiable_id and notifiable_type clauses from the query.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:15