2020_03_25_164834_change_commodities_table.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. use App\Commodity;
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6. class ChangeCommoditiesTable extends Migration
  7. {
  8. /**
  9. * Run the migrations.
  10. *
  11. * 修改commodities表
  12. *
  13. * @return void
  14. */
  15. public function up()
  16. {
  17. ini_set('max_execution_time',2500);
  18. ini_set('memory_limit','1526M');
  19. Schema::table('commodities',function (Blueprint $table){
  20. $table->bigInteger('owner_id')->after('owner_name')->nullable()->comment('外键货主');
  21. });
  22. if (Schema::hasColumn('commodities','owner_name')){
  23. $commodities=Commodity::get();
  24. foreach ($commodities as $commodity){
  25. $owner=\App\Owner::select('id')->where('name',$commodity->owner_name)->first();
  26. if($owner){
  27. $commodity->owner_id=$owner->id;
  28. $commodity->save();
  29. }
  30. }
  31. Schema::table('commodities',function (Blueprint $table){
  32. $table->dropColumn('owner_name');
  33. });
  34. }
  35. }
  36. /**
  37. * Reverse the migrations.
  38. *
  39. * @return void
  40. */
  41. public function down()
  42. {
  43. Schema::table('commodities',function (Blueprint $table){
  44. $table->string('owner_name')->after('owner_id')->nullable()->comment('外键货主');
  45. });
  46. if (Schema::hasColumn('commodities','owner_id')){
  47. $commodities=Commodity::get();
  48. foreach ($commodities as $commodity){
  49. $owner=\App\Owner::select('id','name')->where('id',$commodity->owner_id)->first();
  50. \Illuminate\Support\Facades\DB::table('commodities')->where('id',$commodity->id)->update(['owner_name'=>$owner->name]);
  51. }
  52. Schema::table('commodities',function (Blueprint $table){
  53. $table->dropColumn('owner_id');
  54. });
  55. }
  56. }
  57. }