<?php

use App\Commodity;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ChangeCommoditiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * 修改commodities表
     *
     * @return void
     */
    public function up()
    {

        ini_set('max_execution_time',2500);
        ini_set('memory_limit','1526M');
        Schema::table('commodities',function (Blueprint $table){
            $table->bigInteger('owner_id')->after('owner_name')->nullable()->comment('外键货主');
        });
        if (Schema::hasColumn('commodities','owner_name')){
            $commodities=Commodity::get();
            foreach ($commodities as $commodity){
                $owner=\App\Owner::select('id')->where('name',$commodity->owner_name)->first();
                if($owner){
                    $commodity->owner_id=$owner->id;
                    $commodity->save();
                }
            }
            Schema::table('commodities',function (Blueprint $table){
                $table->dropColumn('owner_name');
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('commodities',function (Blueprint $table){
            $table->string('owner_name')->after('owner_id')->nullable()->comment('外键货主');
        });
        if (Schema::hasColumn('commodities','owner_id')){
            $commodities=Commodity::get();
            foreach ($commodities as $commodity){
                $owner=\App\Owner::select('id','name')->where('id',$commodity->owner_id)->first();
                \Illuminate\Support\Facades\DB::table('commodities')->where('id',$commodity->id)->update(['owner_name'=>$owner->name]);
            }
            Schema::table('commodities',function (Blueprint $table){
                $table->dropColumn('owner_id');
            });

        }
    }
}
