1.2Laravel模型(Model)之迁移(Migration)

在生成迁移之前,需先生成模型。

迁移

php artisan make:migration create_flights_table
<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}
php artisan migrate

查询表

if (Schema::hasTable('users')) {
    // The "users" table exists...
}

if (Schema::hasColumn('users', 'email')) {
    // The "users" table exists and has an "email" column...
}

新增表

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email');
    $table->timestamps();
});

更新表

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('users', function (Blueprint $table) {
    $table->integer('votes');
});

重命名/删除表

use Illuminate\Support\Facades\Schema;

Schema::rename($from, $to);
Schema::drop('users');

Schema::dropIfExists('users');

新增列

Schema::table('users', function (Blueprint $table) {
    $table->integer('votes');
});

更新列

更新列之前一定要安装 doctrine/dbal 包

composer require doctrine/dbal

重命名列

Schema::table('users', function (Blueprint $table) {
    $table->renameColumn('from', 'to');
});

更新列属性

Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});

删除列

Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('votes');
});

索引

新增索引

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->unique();
});

更改索引

$table->renameIndex('from', 'to')

删除索引

Schema::table('geo', function (Blueprint $table) {
    $table->dropIndex(['state']); // Drops index 'geo_state_index'
});

外键约束

//常规写法
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});
//简写
Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained('users');
});

约束删除

您还可以为约束的“删除时”和“更新时”属性指定所需的操作:

$table->foreignId('user_id')
      ->constrained()
      ->onUpdate('cascade')
      ->onDelete('cascade');

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/php/laravel/5554.html

发表评论

登录后才能评论