2020_03_25_164834_change_commodities_table.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. Schema::table('commodities',function (Blueprint $table){
  18. $table->bigInteger('owner_id')->after('owner_name')->nullable()->comment('外键货主');
  19. });
  20. if (Schema::hasColumn('commodities','owner_name')){
  21. $commodities=Commodity::get();
  22. foreach ($commodities as $commodity){
  23. $owner=\App\Owner::select('id')->where('name',$commodity->owner_name)->first();
  24. $commodity->owner_id=$owner->id;
  25. $commodity->save();
  26. }
  27. Schema::table('commodities',function (Blueprint $table){
  28. $table->dropColumn('owner_name');
  29. });
  30. }
  31. }
  32. /**
  33. * Reverse the migrations.
  34. *
  35. * @return void
  36. */
  37. public function down()
  38. {
  39. Schema::table('commodities',function (Blueprint $table){
  40. $table->string('owner_name')->after('owner_id')->nullable()->comment('外键货主');
  41. });
  42. if (Schema::hasColumn('commodities','owner_id')){
  43. $commodities=Commodity::get();
  44. foreach ($commodities as $commodity){
  45. $owner=\App\Owner::select('id','name')->where('id',$commodity->owner_id)->first();
  46. \Illuminate\Support\Facades\DB::table('commodities')->where('id',$commodity->id)->update(['owner_name'=>$owner->name]);
  47. }
  48. Schema::table('commodities',function (Blueprint $table){
  49. $table->dropColumn('owner_id');
  50. });
  51. }
  52. }
  53. }