如何在 Laravel 队列中使用模型 [英] How to use Models in a Laravel Queue

查看:43
本文介绍了如何在 Laravel 队列中使用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将邮件列表从 CSV 导入到我的数据库中.我的 Laravel 中有两个模型负责执行此操作:TargetMailing(一个 Target 有许多 Mailing>s)

I'm trying to import a mailing list from CSV to my DATABASE. I have two models in my Laravel which is responsible for doing this: Target and Mailing (one Target has many Mailings)

我在 Beanstalkd 中使用队列系统.我正在使用:

I'm using Queue system with Beanstalkd. I'm using:

Queue::push('ImportCSV', array(
            'file' => $file->getClientOriginalName(),
            'target' => $name
    ));

要推送我的工作,然后我有 ImportCSV 工作类:

To push my jobs and then I have the ImportCSV job class:

class ImportCSV
{
public function fire($job, $data) 
{   
    Log::info("Starting to add {$data['target']} to database");

    $target = new Target();
    $target->name = $data['target'];
    $target->save();

    $reader = new \EasyCSV\Reader($data['file']);

    // There must be a Email field in CSV file
    /*if(!in_array('Email', $reader->getHeaders() ))
        throw new Exception("Email field not found", 1);*/

    while ($row = $reader->getRow())
    {
        $mailing = new Mailing();
        $mailing->target()->associate($target);
        $mailing->email = $row['Email'];
        $mailing->save();
    }

    Log::info("Mailing list {$target->name} added to database");

    $job->delete();
}
}

所有代码似乎都在工作,因为我在日志文件中收到了这些消息

All the code seems to be working since I get these messages in my Log file

[2013-09-10 21:03:25] log.INFO: Starting to add TEst to database [] []
[2013-09-10 21:03:25] log.INFO: Mailing list TEst added to database [] []

但是没有记录添加到我的数据库中.我应该如何在工作中使用模型?例如,我已经在控制器中对其进行了测试,一切正常

But no records are added to my database. How should I use models inside a job? I already tested it in a Controller for example and everything works fine

推荐答案

由于您没有看到其他错误,我认为这是环境问题.

Since you don't see other errors, I'm thinking this is an environment issue.

确保您对 php artisan queue:listen(或 queue:work,如果适用)的调用使用正确的环境,以便使用正确的数据库:

Make sure your call to php artisan queue:listen (or queue:work, if applicable) is using the correct environment so the correct database is getting used:

$ php artisan queue:listen --env=YOUR_ENV

这是一篇关于 在 Laravel 4 中设置队列 的帖子,它可能对更多信息有帮助信息.

Here's a post on setting up queues in Laravel 4 which might be helpful for more information.

由于您(显然?)没有看到任何 PHP 错误,这不太可能,但是另一个想法:

As you (apparently?) aren't seeing any PHP errors, this is less likely, but another idea:

如果您的类是命名空间的,则可能需要使用 \ 字符来获取位于全局命名空间中的模型.

If your class is namespaced, you may need to use the \ character to get your models, which are in the global namespace.

// From:
$mailing = new Mailing();

// To:
$mailing = new \Mailing();

这篇关于如何在 Laravel 队列中使用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆