Laravel - 定期从数据库表中提取

时间:2018-06-18 16:59:13

标签: php laravel

在Laravel中,我有一个文章表,这是一个月前我在项目开始时从数据库中提取的文章。

此数据库与我的Laravel应用程序是分开的,但内容可能每天都会更改,而且我每三天手动抓取一次内容,您可以想象这需要时间。

我已经看到你可以在Laravel中拥有两个数据库连接,如下所示:

<?php
return array(

'default' => 'mysql',

'connections' => array(

    # Our primary database connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'host1',
        'database'  => 'database1',
        'username'  => 'user1',
        'password'  => 'pass1'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

    # Our secondary database connection
    'mysql2' => array(
        'driver'    => 'mysql',
        'host'      => 'host2',
        'database'  => 'database2',
        'username'  => 'user2',
        'password'  => 'pass2'
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
),

);

那么,如果我有我可以连接的辅助文章表,是否可以创建一个cron作业,每小时将新内容提取到我的Laravel应用程序?

从辅助数据库中提取时,如何避免覆盖内容?

1 个答案:

答案 0 :(得分:1)

您可以像这样

定义辅助数据库的模型
namespace App\Secondary;

class Article extends Model {

    protected $connection = 'mysql2';

    public static function fetchArticles(){
      //fetch articles

      //TODO all other filter to fetch new records
      $articles = Article::all();
       return $articles;
    }
}
  

如何避免覆盖内容?

如果主连接和辅助连接数据库表中都有id或任何标识列,则只需从主连接文章表中获取最新文章标识,然后从辅助数据库表中获取该文件后的新文章。

  

这是调度程序类

namespace App\Console\Commands;

use Illuminate\Console\Command;

class ArticlePuller extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'articlePuller';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pull article from secondary database';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $articles = Secondary/Article::fetchArticles(); //from secondary db table 
        Article::insertArticles($articles); 
    }
}
  

在console / Kernel.php中定义此调度程序

 protected $commands = [
    Commands\ArticlePuller::class
 ];

 protected function schedule(Schedule $schedule)
 {
    $schedule->command('articlePuller')->hourly();
 }
  

现在需要在cron job

中添加此调度程序条目
* * * * * php path_to_artisan/artisan schedule:run >> /dev/null 2>&1