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



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

$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]:找不到列:1054 "字段列表"中的未知列"mymail@domain.com">
(SQL:选择mymail@domain.com来自product_id= 2 的reservations)

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

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

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

你的用法有点错误,pluck方法接受column名称,你传递的是值,即用户电子邮件。所以这就是为什么它说找不到具有该电子邮件地址的列。您可以改为尝试此操作:

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

Notification::send()想要一个应通知实体的集合,而不是电子邮件的集合,所以首先你必须将正确的特征添加到User模型中:

use IlluminateNotificationsNotifiable;
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();

我不知道哪个列存储您的用户名字段。但是假设列名是username.您应该拔掉该列,而不是email。喜欢这个:

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

基本上:在pluck()方法中传递列名

相关内容

最新更新