【发布时间】:2022-01-21 21:27:08
【问题描述】:
我想在获取特定用户的通知时获取notifiable model 关系。另外,我想在通知表中保存并获取自定义变形关系(即causer(causer_id 和causer_type))(就像notifiable)。我能够创建一个变形关系并将其保存到表记录中,但是在获取关系模型时遇到了麻烦,它在两个关系中都返回 null。分享代码。
- 自定义
DatabaseChannel-- 修改后的 buildPayload 方法。
protected function buildPayload($notifiable, Notification $notification)
{
$data = $this->getData($notifiable, $notification);
$causer = $data['causer'];
unset($data['causer']);
return [
// README: removed uuid from here
'type' => method_exists($notification, 'databaseType')
? $notification->databaseType($notifiable)
: get_class($notification),
'data' => $data,
'read_at' => null,
'causer_type' => get_class($causer),
'causer_id' => $causer->id,
];
}
- 自定义
notifiable特征
use Illuminate\Notifications\Notifiable as BaseNotifiable;
trait Notifiable
{
use BaseNotifiable;
/**
* Get the entity's notifications.
*/
public function notifications(): MorphMany
{
return $this->morphMany(Notification::class, 'notifiable')
->orderBy('created_at', 'desc');
}
}
还有一件事我想在这里问一下,我如何将两个变形关系引用到单个表中,比如我想添加 notifications 方法和 causer 以及 notifiable。
- 自定义
Notifications模型
class Notification extends DatabaseNotification
{
public function causer()
{
return $this->morphTo();
}
}
我错过了什么或做错了什么?有没有可能我正在尝试做的事情?
【问题讨论】:
-
你有解决办法吗?我正在寻找同样的东西
-
请看下面的答案
-
我想先添加记录。你是如何在通知表中添加causer_type 和causer_id 的?如果您可以提供一些详细信息,请
-
只需创建迁移并更新
notifications表。 -
我似乎无法在这里正确解释我的问题,我在通知表中添加了自定义通知但我无法存储它。
标签: php laravel notifications laravel-8