migration基本使用

migration基本使用

laravel 特有的对数据库版本的操作,解决团队合作数据库结构不统一的问题,智能化管理数据库结构的一种解决方案

创建表

(*表名为复数形式,model为单数形式)

//创建新表
php artisan make:migration create_表名_table --create=users
//--create=users 命令选项表示使用Schema::create方法,参数为users
//添加表字段
php artisan make:migration add_表名_table --table=users
//--table=users 命令选项表示使用Schema::table方法,参数为users

//laravel/database/migrations/

生成的迁移文件的两个方法

执行 php artisan migrate

public function up(){
//创建表
Schema::create('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});
//修改表
Schema::table('question_dati', function (Blueprint $table) {
            $table->integer('course_type')->nullable()->after('id');
});
//重命名
Schema::rename(表名,重命名);

}

执行 php artisan migrate:rollback

public function down(){
//删除表
Schema::drop('users');
//删除字段
Schema::table('question_dati', function (Blueprint $table) {
            $table->dropColumn(['course_type', 'z_id' , 'j_id']);
 });

}

执行 php artisan migrate --pretend 执行SQL语句

创建表字段属性

increments --- 自增长,主键,不为负数,int长度10
string('字段名') --- 字符串
integer('字段名') --- int 类型
decimal('字段名') --- 浮点型
text('字段名') ---text类型
-- nullable() ---为空 (默认是不为空not null)
-- default(0) ---默认值
-- comment('备注') ---备注


softDeletes() --- 软删除
timestamps() ---时间戳Eloquent 自动维护


unsignedInteger('外键ID') --- 表示不为负数


指定一个表的外键

//表示 本表的外键为 user_id,通过 user表的id字段相关联
$table->foreign('user_id')->references('id')->on('users');

常见问题

  1. 有时候会创建一些错误的database/migrations/目录下文件,又不小心删除了。这时候再执行类似命令回报错,提示找不到文件目录。
php artisan make:migration create_table_user --create=user
//执行 重置composer文件加载项:

composer dump-autoload
  1. 使用laravel 5.4框架数据库迁移时执行 php artisan migrate 报错的问题

[https://laravel-china.org/topics/3852/string-length-problem-caused-by-character-encoding-change-in-laravel-54-mysql-database]

//修改 config/database.php 里的 charset,collation,engine 。

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'databasename'),
            'username' => env('DB_USERNAME', 'dbuser'),
            'password' => env('DB_PASSWORD', 'dbpassword'),
            'charset' => 'utf8',
            'collation' => 'utf8_general_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => 'MYISAM',
        ],

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容