如何使用Laravel迁移 [英] How to use laravel migrations

查看:109
本文介绍了如何使用Laravel迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PHP的Laravel框架进行开发.我想将迁移用于表创建-操作.这些是我采取的步骤:

I am using Laravel framework of php for development. I want to use migration for table creation-manipulation. These are the steps I took:

  1. 我使用命令php artisan migrate:make create_users_table创建迁移,该命令创建了一个迁移文件,并在其up函数中写下了自己的模式,然后运行它并成功执行了该程序.

  1. I create migration with command php artisan migrate:make create_users_table, which create a migration file and in its up function, I wrote down my schema and then I ran it and it got successfully executed.

在那之后,我再次尝试运行相同的迁移,结果显示了表存在"的错误.

After that, I tried again run the same migration and as a result, its shows the error that, 'table exist'.

然后我尝试使用回滚功能,但是它给出了错误什么也不能回滚".

Then I tried to use rollback function but it give error 'nothing to roll back' .

因此,如何回滚该迁移或执行迁移功能.另外,当我创建新迁移并在迁移文件的up函数中时,我编写了用于删除由较早迁移创建的表的代码,并使用命令php artisan migrate执行,由此所有迁移均得以执行(也是我的较早版本),并向我展示了错误,表已存在"(显而易见).

So, how to rollback that migration or to execute down function of migration. Also, when I created new migration and in migration file's up function, I wrote code for dropping table created by my earlier migration and I execute with command php artisan migrate , by this all migration got executed (also my earlier one) and shows me the error, 'table already exist' (obvious).

那么,现在我被困住了,是否有执行特殊/特殊迁移的功能?我该怎么做?

So, now I'm stuck, is there a function to execute a special/particular migration? How do I do this?

推荐答案

使用artisan migrate:make创建迁移时,应编写updown方法. down方法应该做与up方法相反的事情.

When you create a migration with artisan migrate:make you should write the up and down methods. The down method should do the OPPOSITE of what the up method does.

public function up()
{
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('username');
    });
}

public function down()
{
    // We DROP the table because we created it in the "up" method.
    Schema::drop('users');
}

在我看来,您的up方法中有一些不属于该代码的代码,尽管很难看到这些代码.我建议您清除我们的migrations表(可能有也可能没有任何记录).您还需要手动删除通过迁移创建的表.然后,您可以重新开始.

It sounds to me like you have some code in your up method that doesn't belong there, although this is hard to say without seeing your code. I suggest you clear our the migrations table (there may or may not be any records). You'll also need to manually drop the table you created through the migration. Then you can start fresh.

请记住,也可以使用dropIfExists删除表(如果存在).

Remember you can also use dropIfExists to drop a table only if it exists.

public function down()
{
    // Drop the table only if it exists.
    Schema::dropIfExists('users');
}

这篇关于如何使用Laravel迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆