首页 > 解决方案 > 为通知检索用户电子邮件集合

问题描述

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

$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:选择.from mymail@domainwhere = 2)comreservationsproduct_id

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

用户和预订之间的关系是One To Many指用户hasMany预订和用户预订belongsTo

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

标签: phplaravellaravel-5.8

解决方案


您的用法有点错误,该pluck方法接受column名称,您传递的是值,即用户电子邮件。这就是为什么它说找不到包含该电子邮件地址的列的原因。你可以试试这个:

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

推荐阅读