如何在通知中添加关系?并在json中获取相关数据 [英] How to add relations to notifications? And get the related data in json
问题描述
我正在尝试创建关系,并且当通过$user->unreadNotifications
获取通知时,我想控制显示哪些字段并获取关系.我不知道该在哪里做.
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.
我做了以下事情:
-
php artisan notifications:table
-
php artisan make:migration add_relations_to_notifications_table
-
在此新迁移中,我添加了
requester_id
.
php artisan notifications:table
php artisan make:migration add_relations_to_notifications_table
In this new migration I added
requester_id
.
$table->integer('requester_id')->unsigned()->nullable();
$table->foreign('requester_id')->references('id')->on('users')->onDelete('cascade');
php migrate
然后在AnInviteWasRequested
中,我删除了toArray
并将其替换为toDatabase
:
Then in AnInviteWasRequested
I removed the toArray
and replaced it with toDatabase
:
public function toDatabase($notifiable)
{
return [
'requester_id' => Auth::guard('api')->user()->id
];
}
但是这并没有设置requester_id
字段,它只是将json放入data
列中,如下所示:{"requester_id":1}
.
However this does not set the requester_id
field, it just put json into the data
column that looks like this: {"requester_id":1}
.
反正有没有办法让它更新requester_id
字段而不是更新data
?
Is there anyway to get this to update the requester_id
field instead of updating data
?
在$user->unreadNotifications
完成后,是否可以在某个地方(例如模型文件(不在vendor
目录中)控制在哪个字段中显示内容?)
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?
推荐答案
实际上是定义要显示/保存的字段,然后需要显示它,只需修改toDatabase
方法即可.示例:
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. :)
这篇关于如何在通知中添加关系?并在json中获取相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!