doukengzi3517 2016-04-07 18:39
浏览 82
已采纳

Laravel一次添加多个作业

For a user action, I need to send email to all of his subscribers. In this case, the emails should be queued to send later.

I used jobs for that, which can accept single user instance at a time (followed Laravel Doc) and it inserts a job in job table. This is fine.

Now, as the subscribers number is more that one, how can I add multiple user instance or jobs at a time in the jobs table? In Laravel 5.2, how can I achieve that?

  • 写回答

1条回答 默认 最新

  • dongyan9838 2016-04-07 18:56
    关注

    I'm not sure if i'm missing something here by reading your question, but if you are implementing your own job queue, couldnt you just change the constructor to accept an collection (array) of users instead and in the handle method simply run a foreach which would email them?

    Example in Laravel docs modified to accept a collection of users instead of single user:

    <?php
    
    
    namespace App\Jobs;
    
    use App\User;
    use App\Jobs\Job;
    use Illuminate\Contracts\Mail\Mailer;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class SendReminderEmail extends Job implements ShouldQueue
    {
      use InteractsWithQueue, SerializesModels;
    
    protected $users = [];
    
    /**
     * Create a new job instance.
     *
     * @param  User  $user
     * @return void
     */
    public function __construct($users) //Pass in an array of your user objects
    {
        $this->users = $users;
    }
    
    /**
     * Execute the job.
     *
     * @param  Mailer  $mailer
     * @return void
     */
    public function handle(Mailer $mailer)
    {
      foreach($users as $currentUser){
          $mailer->send('emails.reminder', ['user' => $currentUser], function ($){
            //code here
        });
    
        $currentUser->reminders()->create(...);
       }
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题