如何将模型添加到 laravel 通知并使用 eloquent 访问它?

How to add model to laravel notifications and access it with eloquent?

我创建了 laravel 通知 class

php artisan make:notification NewUserNotification

class NewUserNotification extends Notification
{
use Queueable;
protected $cost;
private  $order_id;

/**
 * Create a new notification instance.
 *
 * @return void
 */
public function __construct($cost, $order_id)
{
    $this->cost = $cost;
    $this->order_id = $order_id;
}



/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return [CustomDbChannel::class];
}

/**
 * Get the mail representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return \Illuminate\Notifications\Messages\MailMessage
 */
public function toMail($notifiable)
{
    return (new MailMessage)
        ->line('The introduction to the notification.')
        ->action('Notification Action', url('/'))
        ->line('Thank you for using our application!');
}

/**
 * Get the array representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return array
 */

public function toDatabase($notifiable)
{
    $a = $this->cost;
    return [
        'cost' => $a,
        'order_id' => $this->order_id,
    ];
}

public function toArray($notifiable)
{
    return [
        'cost' => $this->cost,
    ];
}
}

然后创建一个自定义 DbChannel 来添加订单 ID

class CustomDbChannel
{

public function send($notifiable, Notification $notification)
{
    $data = $notification->toDatabase($notifiable);

    return $notifiable->routeNotificationFor('database')->create([
        'id' => $notification->id,

        //customize here
        'order_id' => $data['order_id'], //<-- comes from toDatabase() Method below

        'type' => get_class($notification),
        'data' => $data,
        'read_at' => null,
    ]);
}
}

一切正常,我可以访问 Auth::user-> 通知但不能访问订单,我有 order_id 作为外键并且可以通过单击访问 phpMyAdmin 中的订单在上面,我试过了但是它给了我 null

$notifications->order

您可以使用 $order = Order::find($data['order_id']),前提是您已将 Order class 导入到您的命名空间中。我认为这可能是最简单的方法。