我想在获取特定用户的通知时获取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 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');
}
}
还有一件事我想问,我如何将两个变形关系引用到一个表中,就像我想用causer
和notifiable
添加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');
});
}