检索用于通知的用户电子邮件集合

Retrieving a collection of user emails for Notification

我想安排一个任务,在满足特定条件时向已预订特定产品的选定用户发送电子邮件通知。以下是任务的设置方式

$schedule->call(function () {

    // get reservation collection
    $reservations = Reservation::all();

    // iterate over reservation collection
    foreach ($reservations as $reservation) {

        // get difference in hours between now and product start date
        $timeDiff = Carbon::parse($reservation->product->start)->diffInHours();

        // send mail notification to reservation owners
        if ($timeDiff > 2) {

            // get users who reserved the product
            $users = Reservation::where('product_id', $reservation->product_id)->pluck($reservation->user->username);

            //notify user
            Notification::send($users, new ReservedProductPurchase($reservation));
        }
    }
})->everyMinute();

当我运行命令php artisan schedule:run时,它抛出一个错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'mymail@domain.com' in
'field list' (SQL: select mymail@domain.com from reservations where product_id = 2)

当然,我没有在预订中保存电子邮件(在本例中为用户名)table,这就是发生错误的原因。

用户和预订之间的关系是 One To Many,这意味着用户 hasMany 预订和预订 belongsTo 用户。

我应该如何检索我希望将通知发送到的电子邮件(用户名)集合?

我不知道什么列存储您的用户名字段。但假设列名是 username。您应该选择该列,而不是 email。像这样:

$users = Reservation::where('product_id', $reservation->product_id)->pluck('username');

基本上:在pluck()方法

中传递列名

你的用法有点不对,pluck方法接受的是column名字,你传递的是值,也就是用户邮箱。所以这就是为什么它说找不到具有该电子邮件地址的列。您可以试试这个:

Reservation::with('user')
    ->where('product_id', $reservation->product_id)
    ->get()
    ->pluck('user.email')
    ->toArray()

Notification::send() 想要一组 可通知实体 而不是一组电子邮件,因此首先您必须添加正确的 特征 User 模型:

use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
    use Notifiable;
}

然后你可以检索有一定保留的用户:

// get users who reserved the product
$users = User::whereHas('reservations', function (Builder $query) use ($reservation)
{
    $query->where('product_id', $reservation->product_id);
})->get();