0

在 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 应用程序?

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

4

1 回答 1

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 或任何标识列,那么只需从主连接文章表中获取最新的文章 ID 并从辅助数据库表中获取该 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 作业中添加这个调度程序条目

* * * * * php path_to_artisan/artisan schedule:run >> /dev/null 2>&1
于 2018-06-18T17:21:55.750 回答