Allow postgis location data to be copied to float columns

This commit is contained in:
Jonny Barnes 2020-10-10 20:56:29 +01:00
parent fad7a4be0f
commit 0993d0187f
2 changed files with 118 additions and 0 deletions

View file

@ -0,0 +1,84 @@
<?php
namespace App\Console\Commands;
use App\Models\Place;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class MigratePlaceDataFromPostgis extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'places:migratefrompostgis';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Copy Postgis data to normal latitude longitude fields';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$locationColumn = DB::selectOne(DB::raw("
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name = 'places'
AND column_name = 'location'
)
"));
if (!$locationColumn->exists) {
$this->info('There is no Postgis location data in the table. Exiting.');
return 0;
}
$latitudeColumn = DB::selectOne(DB::raw("
SELECT EXISTS (
SELECT 1
FROM information_schema.columns
WHERE table_name = 'places'
AND column_name = 'latitude'
)
"));
if (!$latitudeColumn->exists) {
$this->error('Latitude and longitude columns have not been created yet');
return 1;
}
$places = Place::all();
$places->each(function ($place) {
$this->info('Extracting Postgis data for place: ' . $place->name);
$place->latitude = $place->location->getLat();
$place->longitude = $place->location->getLng();
$place->save();
});
return 0;
}
}

View file

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddLatitudeLongitudeColumns extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('places', function (Blueprint $table) {
$table->float('latitude')->nullable();
$table->float('longitude')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('places', function (Blueprint $table) {
$table->dropColumn('latitude');
$table->dropColumn('longitude');
});
}
}