获得可通知并在Laravel通知中实现自定义变形关系



我想在获取特定用户的通知时获取notifiable model关系。另外,我想在通知表中保存并获取自定义变形关系(即causer(causer_idcauser_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 IlluminateNotificationsNotifiable 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');
}
}

还有一件事我想问,我如何将两个变形关系引用到一个表中,就像我想用causernotifiable添加notifications方法一样。

  • 自定义Notifications型号
class Notification extends DatabaseNotification
{
public function causer()
{
return $this->morphTo();
}
}

我错过了什么或做错了什么?我想做的事情有可能吗?

为了获得变形关系(一个或两个(,您需要选择列{morph}_id{morph}_type,这只是为了防止在获取记录时使用->select(),如果不使用select,则不会产生任何问题。

编辑

以下是如何将自定义列添加到notifications

public function up()
{
Schema::table('notifications', function (Blueprint $table) {
$table->string("causer_type")->after('notifiable_id');
$table->unsignedInteger("causer_id")->after('causer_type');
$table->index(["causer_type", "causer_id"]);
});
}
public function down()
{
Schema::table('notifications', function (Blueprint $table) {
$table->dropMorphs('causer');
});
}

最新更新