2018_01_01_000000_create_regions_table.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. use Cblink\Region\Region;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Schema;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Database\Migrations\Migration;
  7. use Lybc\PhpGB2260\GB2260;
  8. class CreateRegionsTable extends Migration
  9. {
  10. public function up()
  11. {
  12. Schema::create('areas', function (Blueprint $table) {
  13. $table->increments('id');
  14. $table->unsignedInteger('parent_id')->nullable()->index();
  15. $table->string('name');
  16. $table->unsignedTinyInteger('type');
  17. $table->unsignedInteger('code');
  18. });
  19. $region = new Region();
  20. $provinces = $region->getRegionsWithCode();
  21. foreach ($provinces as $province) {
  22. $provinceId = DB::table('areas')->insertGetId([
  23. 'name' => $province['title'],
  24. 'code' => $province['ad_code'],
  25. 'type' => Region::PROVINCE,
  26. ]);
  27. foreach ($province['child'] as $city) {
  28. $cityId = DB::table('areas')->insertGetId([
  29. 'name' => $city['title'],
  30. 'parent_id' => $provinceId,
  31. 'code' => $city['ad_code'],
  32. 'type' => Region::CITY,
  33. ]);
  34. $areas = array_map(function ($area) use ($cityId) {
  35. return ['name' => $area['title'], 'code' => $area['ad_code'], 'parent_id' => $cityId, 'type' => Region::AREA];
  36. }, $city['child']);
  37. DB::table('areas')->insert($areas);
  38. }
  39. }
  40. }
  41. public function down()
  42. {
  43. Schema::dropIfExists('areas');
  44. }
  45. }