Created
November 30, 2017 18:45
-
-
Save DfKimera/16ddbc8e5e1b7d3028d7ae7f10ecf9fb to your computer and use it in GitHub Desktop.
Command line Laravel tool to migrate data from a MySQL connection to a SQLite connection, preserving IDs and data structures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* espp-site | |
* ExportDataToSQLite.php | |
* | |
* Copyright (c) LQDI Digital | |
* www.lqdi.net - 2017 | |
* | |
* @author Aryel Tupinambá <[email protected]> | |
* | |
* Created at: 30/11/2017, 16:26 | |
*/ | |
namespace App\Console\Commands; | |
use Illuminate\Console\Command; | |
use Illuminate\Database\Eloquent\Model; | |
class ExportDataToSQLite extends Command { | |
protected $signature = "maintenance:export_data_to_sqlite"; | |
public function handle() { | |
$models = [ | |
new \App\Category(), | |
new \App\Faq(), | |
new \App\Product(), | |
new \App\Section(), | |
new \App\User() | |
]; | |
foreach($models as $model) { /* @var $model Model */ | |
$this->info("Processing model: " . get_class($model)); | |
$model->setConnection('mysql'); | |
$query = $model->query(); | |
if(method_exists($query, 'withTrashed')) { | |
$this->comment("\tHas soft delete, will include trashed entries"); | |
$query->withTrashed(); | |
} | |
$data = $query->get(); | |
$this->comment("\tFetched data, count=" . sizeof($data)); | |
$sqliteModel = (clone $model); | |
$sqliteModel->setConnection('sqlite'); | |
$this->comment("\tInserting data into SQLite..."); | |
foreach($data as $row) { | |
$instance = clone $sqliteModel; | |
$instance->setRawAttributes($row->toArray()); | |
$instance->save(); | |
$this->comment("\t\tMySQL ID={$row->id} -> SQLite ID={$instance->id}"); | |
} | |
$this->comment("\tCompleted data transfer!"); | |
} | |
$this->comment("\tCompleted all models!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment