【问题标题】:getting notifiable and implementing custom morph relation in Laravel notification在 Laravel 通知中获取通知并实现自定义变形关系
【发布时间】:2022-01-21 21:27:08
【问题描述】:

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


【解决方案1】:

为了获得变形关系(一个或两个),您需要选择列{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');
        });
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多