我想安排一項任務,該任務將在滿足特定條件時向已預訂特定產品的選定用戶發送電子郵件通知。這是任務的設置方式$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 未知列“字段列表”中的“[email protected] ”(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 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消