我想安排一项任务,该任务将在满足特定条件时向已预订特定产品的选定用户发送电子邮件通知。这是任务的设置方式$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. comfrom reservationswhere product_id= 2)当然,我没有在我的预订表中保存电子邮件(在这种情况下为用户名),这就是发生错误的原因。用户和预约的关系是One To Many用户hasMany预约和用户预约belongsTo。我应该如何检索我希望将通知发送到的电子邮件(用户名)集合?
3 回答
米脂
TA贡献1836条经验 获得超3个赞
你的用法有点不对,pluck
方法接受的是column
名字,你传的是值,也就是用户邮箱。所以这就是为什么它说找不到带有该电子邮件地址的列的原因。你可以试试这个:
Reservation::with('user') ->where('product_id', $reservation->product_id) ->get() ->pluck('user.email') ->toArray()
斯蒂芬大帝
TA贡献1827条经验 获得超8个赞
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();
回首忆惘然
TA贡献1847条经验 获得超11个赞
我不知道哪个列存储您的用户名字段。但假设列名是username
. 您应该选择该列,而不是email
. 像这样:
$users = Reservation::where('product_id', $reservation->product_id)->pluck('username');
基本上:在pluck()
方法中传递列名
- 3 回答
- 0 关注
- 142 浏览
添加回答
举报
0/150
提交
取消