laravel - 拉拉维尔。如何获取数据库通知的ID?
问题描述
我使用数据库通知,在通知代码中我有方法toDatabase
:
public function toDatabase($notifiable)
{
$user = \App\SomeUsers::where('id', $notifiable->id)->first();
return [
'message' => $message,
];
}
它返回正在发送到via
当前通知方法中提到的数据库通道的数据数组:
public function via($notifiable)
{
return ['database'];
}
一切都像往常一样,但是......问题是我需要在当前通知文件中的数据库中通知 id,以便我可以将消息(来自当前通知文件)广播到包含 db 中通知 id 的前端(所以我可以以某种方式识别它以标记为已读)。如何得到它?
PS 此外,数据库通知可能是可排队的,所以...似乎我无法获取 id... PPS 另一个词我需要包含的广播消息["id" => "id of just added corresponding database notification"]
。
解决方案
<?php
namespace App\Notifications;
use App\Channels\SocketChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Redis;
class MyCustomNotification extends Notification implements ShouldQueue
{
use Queueable;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct($param)
{
$this->param = $param;
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
$channels = ['database'];
return $channels;
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toDatabase($notifiable)
{
info("This is the current notification ID, it's generated right here before inserting to database");
info($this->id);
return [
'id' => **$this->id**,
'message' => 'Notification message',
];
}
}
$this->id解决了这个问题。
https://laracasts.com/discuss/channels/laravel/get-database-notification-id-in-push-notification
PS我想提请注意一个事实。当我发布这个问题时,我知道$this->id,但我无法让它发挥作用。原因是:当我从顶层深入研究目标代码时,我对代码进行了更改,但它们并不适用。原因是排队。您需要重新启动 laravel worker 以将设置应用为 Laravel 缓存逻辑,或者您需要暂时删除这些设置:实现 ShouldQueue 并使用 Queueable。
推荐阅读
- amazon-web-services - 使用 aws cli 将 Lambda 与 REST 端点集成
- google-sheets - 谷歌电子表格 - hlookup 使用 arrayformula 应用于新行
- mysql - MySQL:从每日记录中插入每月值
- javascript - 如何在不使用 cookie 且不编写后端代码的情况下跨页面跟踪用户?
- javascript - 密码确认后如何将用户重定向到url?
- jquery - 完整的日历标题选项作为下拉导航
- google-apps-script - 使用脚本和网络应用程序将数据从一张 Google 表格复制到另一张表格
- apache - .htaccess 重写为小写
- cassandra - metadata.getTokenRanges() 是否返回 cassandra 中所有节点的所有令牌范围?
- c++ - 使用分层状态机简化平面状态机