PHP项目Laravel数据库通知存储位置

wen PHP项目 6

本文目录导读:

PHP项目Laravel数据库通知存储位置

  1. 默认表结构
  2. 数据库配置
  3. 使用独立数据库存储
  4. 配置文件方式
  5. 自定义通知存储
  6. 查询和操作
  7. 注意事项

在 Laravel 项目中,数据库通知默认存储在 notifications 表中,以下是详细的配置和说明:

默认表结构

Laravel 自带 notifications 表迁移文件,可以通过以下命令创建:

php artisan notifications:table
php artisan migrate

默认表结构包含:

Schema::create('notifications', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->string('type');
    $table->morphs('notifiable');
    $table->text('data');
    $table->timestamp('read_at')->nullable();
    $table->timestamps();
});

数据库配置

config/database.php 中配置通知使用的数据库连接:

'connections' => [
    // 默认连接
    'mysql' => [...],
    // 可以配置独立的通知数据库
    'notification_db' => [
        'driver' => 'mysql',
        'host' => env('NOTIFICATION_DB_HOST', '127.0.0.1'),
        'port' => env('NOTIFICATION_DB_PORT', '3306'),
        'database' => env('NOTIFICATION_DB_DATABASE', 'notifications'),
        'username' => env('NOTIFICATION_DB_USERNAME', 'root'),
        'password' => env('NOTIFICATION_DB_PASSWORD', ''),
        // ...
    ],
],

使用独立数据库存储

如果不想使用默认数据库,可以通过模型定义指定:

// app/Models/Notification.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
    protected $connection = 'notification_db'; // 指定独立数据库
    protected $table = 'notifications';
    // 其他模型代码...
}

配置文件方式

config/notifications.php 中可以配置:

return [
    'database' => [
        'connection' => 'notification_db', // 数据库连接
        'table' => 'notifications',        // 表名
    ],
];

自定义通知存储

如果需要完全自定义存储方式,可以实现 NotificationDatabaseChannel

// app/Channels/CustomDatabaseChannel.php
namespace App\Channels;
use Illuminate\Notifications\Channels\DatabaseChannel;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\DB;
class CustomDatabaseChannel extends DatabaseChannel
{
    public function send($notifiable, Notification $notification)
    {
        // 自定义存储逻辑,例如写入 MongoDB 或其他数据库
        DB::connection('mongodb')->collection('user_notifications')->insert([
            'user_id' => $notifiable->getKey(),
            'data' => $this->getData($notifiable, $notification),
            // ...
        ]);
    }
}

AppServiceProvider 中注册:

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Notification;
use App\Channels\CustomDatabaseChannel;
public function boot()
{
    Notification::extend('database', function ($app) {
        return new CustomDatabaseChannel();
    });
}

查询和操作

// 获取用户通知(使用指定连接)
$user = User::on('notification_db')->find(1);
$notifications = $user->notifications;
// 未读通知
$unread = $user->unreadNotifications;
// 标记为已读
$user->notifications->markAsRead();

注意事项

  • 性能优化:大量通知数据建议使用独立数据库或缓存
  • 数据分区:可以根据时间或用户ID进行表分区
  • 备份策略:通知数据通常需要定期清理或归档
  • 监控:独立数据库需要配置监控和告警

Laravel 默认使用 notifications 表存储数据库通知,可以通过修改模型连接、配置文件或自定义通道来实现使用独立数据库存储的需求。

抱歉,评论功能暂时关闭!