How to add relations to notifications? And get the related data in json

拜拜、爱过 提交于 2019-12-11 14:15:56

问题


I am trying to create relations, and when notifications are fetched via $user->unreadNotifications I want to control which fields are shown, and fetch the relations. I cannot figure out where to do this.

I did the following:

  1. php artisan notifications:table
  2. php artisan make:migration add_relations_to_notifications_table
  3. In this new migration I added requester_id.

    $table->integer('requester_id')->unsigned()->nullable();
    $table->foreign('requester_id')->references('id')->on('users')->onDelete('cascade');
    
  4. php migrate

  5. php artisan make:notification AnInviteWasRequested

Then in AnInviteWasRequested I removed the toArray and replaced it with toDatabase:

public function toDatabase($notifiable)
{
    return [
        'requester_id' => Auth::guard('api')->user()->id
    ];
}

However this does not set the requester_id field, it just put json into the data column that looks like this: {"requester_id":1}.

Is there anyway to get this to update the requester_id field instead of updating data?

And also is it possible somewhere, like a Model file (not in vendor dir) to control which fields are displayed when $user->unreadNotifications is done?


回答1:


Actually to define which field to show/save, and then you need it to display, you only need to modify the toDatabase method. Example:

public function toDatabase($notifiable)
{
    $user = Auth::guard('api')->user();

    return [
        'requester_id' => $user->id,
        'requester_name' => $user->name,
        // and more data that you need to show
    ];
}

So for relational data or any other data, just define it inside this method. Hope it helps. :)



来源:https://stackoverflow.com/questions/48259987/how-to-add-relations-to-notifications-and-get-the-related-data-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!