Laravel 5.3 - 用户收集的单个通知(关注者)更新 2017-01-14:实施了更正确的方法如何使它工作?

2022-08-30 18:35:14

当我有一个用户时,表中会插入一个条目,以及一个通过通道完美工作的/sent。notifiablenotificationsmailsms

问题是当我有一个集合,一个关注我的1000个用户列表,并且我发布更新时。以下是按照多用户案例的建议使用该特征时发生的情况:userNotifiable

  1. 1k / 已发送(问题不在这里)mailssms
  2. 1000 个通知条目添加到数据库的表中notifications

似乎向数据库的表添加 1000 个通知并不是最佳解决方案。由于数据是相同的,并且数据库表中的其他所有内容对于 1k 行都是相同的,一的区别是 .notificationstoArraynotificationsnotifiable_idusernotifiable_type

开箱即用的最佳解决方案是:

  1. Laravel会接受这样一个事实,即它是一个array notifiable_type
  2. 单个通知另存为或以 0 保存(零仅用于表示它是多通知用户)notifiable_typeuser_arrayusernotifiable_id
  3. 创建/使用另一个表,使用刚刚创建的作为并插入1k行,仅包含以下字段:notifications_readnotification_idforeign_key

    notification_id notifiable_id notifiable_type read_at

我希望已经有一种方法可以做到这一点,就像我在我的应用程序中的这一点一样,并且希望在这种情况下使用内置的通知和通道,因为我正在触发/通知,我认为重复1k次是可以的,但是将相同的数据输入数据库是需要优化的问题。emailssms

在这种情况下如何进行的任何想法/想法?


答案 1

更新 2017-01-14:实施了更正确的方法

简单示例:

use Illuminate\Support\Facades\Notification;
use App\Notifications\SomethingCoolHappen;

Route::get('/step1', function () {
    // example - my followers
    $followers = App\User::all();

    // notify them
    Notification::send($followers, new SomethingCoolHappen(['arg1' => 1, 'arg2' => 2]));
});

Route::get('/step2', function () {
    // my follower
    $user = App\User::find(10);

    // check unread subnotifications
    foreach ($user->unreadSubnotifications as $subnotification) {
        var_dump($subnotification->notification->data);
        $subnotification->markAsRead();
    }
});

如何使它工作?

步骤 1 - 迁移 - 创建表(子通知)

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateSubnotificationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('subnotifications', function (Blueprint $table) {
            // primary key
            $table->increments('id')->primary();

            // notifications.id
            $table->uuid('notification_id');

            // notifiable_id and notifiable_type
            $table->morphs('notifiable');

            // follower - read_at
            $table->timestamp('read_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('subnotifications');
    }
}

步骤 2 - 让我们为新的子注释表创建一个模型

<?php
// App\Notifications\Subnotification.php
namespace App\Notifications;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\DatabaseNotificationCollection;

class Subnotification extends Model
{
    // we don't use created_at/updated_at
    public $timestamps = false;

    // nothing guarded - mass assigment allowed
    protected $guarded = [];

    // cast read_at as datetime
    protected $casts = [
        'read_at' => 'datetime',
    ];

    // set up relation to the parent notification
    public function notification()
    {
        return $this->belongsTo(DatabaseNotification::class);
    }

    /**
     * Get the notifiable entity that the notification belongs to.
     */
    public function notifiable()
    {
        return $this->morphTo();
    }

    /**
     * Mark the subnotification as read.
     *
     * @return void
     */
    public function markAsRead()
    {
        if (is_null($this->read_at)) {
            $this->forceFill(['read_at' => $this->freshTimestamp()])->save();
        }
    }
}

步骤 3 - 创建自定义数据库通知通道
更新:使用静态变量 $map 保留第一个通知 ID 并插入下一个通知(使用相同的数据),而无需在表中创建记录notifications

<?php
// App\Channels\SubnotificationsChannel.php
namespace App\Channels;

use Illuminate\Notifications\DatabaseNotification;
use Illuminate\Notifications\Notification;

class SubnotificationsChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed                                  $notifiable
     * @param  \Illuminate\Notifications\Notification $notification
     *
     * @return void
     */
    public function send($notifiable, Notification $notification)
    {
        static $map = [];

        $notificationId = $notification->id;

        // get notification data
        $data = $this->getData($notifiable, $notification);

        // calculate hash
        $hash = md5(json_encode($data));

        // if hash is not in map - create parent notification record
        if (!isset($map[$hash])) {
            // create original notification record with empty notifiable_id
            DatabaseNotification::create([
                'id'              => $notificationId,
                'type'            => get_class($notification),
                'notifiable_id'   => 0,
                'notifiable_type' => get_class($notifiable),
                'data'            => $data,
                'read_at'         => null,
            ]);

            $map[$hash] = $notificationId;
        } else {
            // otherwise use another/first notification id
            $notificationId = $map[$hash];
        }

        // create subnotification
        $notifiable->subnotifications()->create([
            'notification_id' => $notificationId,
            'read_at'         => null
        ]);
    }

    /**
     * Prepares data
     *
     * @param mixed                                  $notifiable
     * @param \Illuminate\Notifications\Notification $notification
     *
     * @return mixed
     */
    public function getData($notifiable, Notification $notification)
    {
        return $notification->toArray($notifiable);
    }
}

步骤 4 - 创建通知
更新:现在通知支持所有通道,而不仅仅是子通知

<?php
// App\Notifications\SomethingCoolHappen.php
namespace App\Notifications;

use App\Channels\SubnotificationsChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class SomethingCoolHappen extends Notification
{
    use Queueable;

    protected $data;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        /**
         * THIS IS A GOOD PLACE FOR DETERMINING NECESSARY CHANNELS
         */
        $via = [];
        $via[] = SubnotificationsChannel::class;
        //$via[] = 'mail';
        return $via;
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', 'https://laravel.com')
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return $this->data;
    }
}

第5步 - “追随者”的帮助者特征

<?php
// App\Notifications\HasSubnotifications.php
namespace App\Notifications;

trait HasSubnotifications
{
    /**
     * Get the entity's notifications.
     */
    public function Subnotifications()
    {
        return $this->morphMany(Subnotification::class, 'notifiable')
            ->orderBy('id', 'desc');
    }

    /**
     * Get the entity's read notifications.
     */
    public function readSubnotifications()
    {
        return $this->Subnotifications()
            ->whereNotNull('read_at');
    }

    /**
     * Get the entity's unread notifications.
     */
    public function unreadSubnotifications()
    {
        return $this->Subnotifications()
            ->whereNull('read_at');
    }
}

步骤6 - 更新您的用户模型
更新:不需要关注者方法

namespace App;

use App\Notifications\HasSubnotifications;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * Adding helpers to followers:
     *
     * $user->subnotifications - all subnotifications
     * $user->unreadSubnotifications - all unread subnotifications
     * $user->readSubnotifications - all read subnotifications
     */
    use HasSubnotifications;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

答案 2

是的,你是对的,我想使用默认特征,你可以创建自定义频道Notifiable

您可以检查该类是否默认创建,并将其采用到数据透视表。Illuminate\Notifications\Channels\DatabaseChannel

希望这有助于创建一个带有数据透视表的新通道。此外,实现一个特征(或类似的名称)到你自己的特征。HasDatabasePivotNotificationsNotifiable


推荐