2016-03-24 4 views
2

私のLaravelプロジェクトでは、私はURLを介して取得するデータベースを持っています。 このデータベースはjsonにあります。私のプロジェクト仕様に従って、ローカルプロジェクトでデータベースをソートし、月ごとに最新のものにするために毎月のcronを作成する必要があります。データベースシーダーを自動的に起動するためにcronを作成する

データを回復することはそれほど難しくありませんが、このデータでシーダーを作成する必要があります。私は毎月のcronを使ってinitailデータを最新のものにするのと同じように、データベースシーダーのための毎月のcronを実装する方法がありますか?

具体的には、これは私のCronController.phpに初期データを回復するために私のcronです:

public static function updateJson(Request $request) 

{ 
    $type="application/json"; 
    $charset="utf-8"; 
    $path = 'database/market.json'; 

    $time=filemtime($path); 
    $update=date("Y-M-d",$time); 

    $updateMonth= date('Y-M-d',strtotime('+1 month',strtotime($update))); 

    $now = date('Y-M-d'); 

    if($now >= $updateMonth) 
    { 
    $data = file_get_contents('url/for/the/public/database'); 

    $data = mb_convert_encoding($data, 'HTML-ENTITIES'); 
    $res= file_put_contents($path, $data); 

    $whatIReallyNeed='update ok'; 

    return response()->json($whatIReallyNeed)->header('Content-type', $type, 'charset', $charset); 

    } else { 

    $error = 'no need to update'; 
    return response()->json($error)->header('Content-type', $type, 'charset', $charset); 
    } 
} 

例えば、私は私のデータベースに町のテーブルを持って、このテーブルの移行を確認してください。

class CreateTownTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('town', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('name', 255); 
      $table->timestamps(); 
      $table->softDeletes(); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::drop('town'); 
    } 
} 

とJSONデータベースTownTableSeeder.phpから件のデータを登録するシーダ:

public function run() 
{ 
    $path = "public/database/market.json"; 
    // get contents of file 
    $json = file_get_contents($path); 
    // decode json datas 
    $datas = json_decode($json, TRUE); 
    // get the multi json array 
    $arrayFeatures = $datas["features"]; 
    // define a new empty array 
    $arrayTown = array(); 
    // populate the new array with values we need 
    foreach ($arrayFeatures as $feature) { 
    array_push($arrayTown, $feature["properties"]["commune"]); 
    } 
    // get unique entry for array 
    $results = array_unique($arrayTown); 
    // get only vales of array after do array_unique (no index) 
    $whatIReallyNeed = array_values($results); 
    foreach ($results as $result) { 
    DB::table('town')->insert([ 
     'name' => $result, 
    ]); 
    } 
} 

これはうまくいきました。今では、cronが私のプロジェクトに保存しているjsonデータベースを更新したときにシードの移行を開始できるかどうか疑問に思っていました。

答えて

1

Laravel Eventsを使用できます。 cronがjsonデータを更新するとき、ちょうどfire an event。マニュアルから

例:

Event::fire(new PodcastWasPurchased($podcast)); 
+0

は、あなたの答えをありがとう、私は私の全体Laravelイベントを構築していない場合でも、(それは仕方によって良いフレームワークです)Laravel5に新しいです、それ良い解決策だと思われるので、私はあなたの答えを検証します。私のコードがビルド全体になると、私はイベントを投稿します。誰かを助けることができるかもしれません。良い一日と幸せなコーディングを! –

関連する問題