注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

@fc_lamp

关注Web应用解决方案MySql/PHP/Python一盏名为"飞川"的灯~

 
 
 

日志

 
 

laravel4框架如何创建迁移(migrations)  

2013-07-04 16:36:04|  分类: Web技术-Php |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
英文源文:http://codehappy.daylerees.com/migrations (注:此篇文章是以laravel3版本为基础的。)

Originally I had attempted to include a guide to the Fluent Query Builder with this chapter, but I now feel that the chapter has become too long, so I have decided to cover database setup and migrations only in this chapter. Get ready for a nice long explanation of Fluent in the next chapter. Migrations are one of my favorite Laravel features, I hate writing SQL, and the Schema class allows me to create my tables easily, without writing a single line of that foul "language"! Not only that, the Schema code looks absolutely beautiful and reads like a book. If you have not encountered migrations before, they are a way of describing changes to your database in files, so that different installations / development copies of your application are aware of the current schema. Changes to the schema can also be reverted or 'rolled back'. Migrations can also be used to populate tables with example data (also known as seeding).

Database Setup 
Head over to your application/config/database.php(fc_lamp注:laravel4版本数据库配置文件在:appl/config/database.php) config file, if you have ever installed a PHP application you will be familiar with this kind of file, you have your database access credentials to hand don't you? If not go dig them out right now! Are you back yet? Great, let's take a closer look. Scroll down to the 'connections' array key, here you will see a number of options for a few different type of databases, fill in the connection parameters for your database of choice, I am going to stick to good ole' fashioned mySQL. 

  • <?php
  • 'mysql' => array(
  •  'driver' => 'mysql',
  •  'host' => 'localhost',
  •  'database' => 'codefun',
  •  'username' => 'root',
  •  'password' => 'pandaseatbamboo',
  •  'charset' => 'utf8',
  •  'prefix' => '',
  • )
  • There we go, now you will want to scroll up a little bit, and change the 'default' array key to reflect the database you are using. For me it's already on mySQL. 

  • <?php
  • 'default' =>'mysql',
  • Now we have our database configured, we need some tables to play with. Onwards to migrations! 
    fc_lamp注:这一歩主要就是设置数据库的配置文件。

    Migrations 
    Let's get started by creating a migration file. We are going to use Laravel's command line interface artisan to create our new migration. To run Artisan you will need to have PHP CLI installed (normally this will be installed along side your web-server). You will also need to open a terminal to the root of your Laravel package where the 'artisan' file exists. Right, let's type our first artisan command : 

    php artisan migrate:make create_users

    We are telling artisan, to run the make method on the migrate task, we pass a name for our migration to identify it by, I like to name it after the action being performed, in this case we are creating the users table.
    Lets have a look at the result.
    Great! New migration created!

    Enthusiastic! If we take a look in our application/migrations(fc_lamp注:laravel4版本中:app/database/migrations) folder, we see a new file named 2012_03_30_220459_create_users.php, well yours might not be called that! You see artisan takes the current date, and adds the time in His format to create the file name. The reason for this is that dates are very important to migrations (and single people), the system needs to be able to know in which order to apply the changes. Let's open up the file and take a look at the migration class. 

  • <?php
  • class Create_Users {
  •  /**
  • * Make changes to the database.
  • *
  • * @return void
  • */
  •  public function up()
  •  {
  •  //
  •  }
  •  /**
  • * Revert the changes to the database.
  • *
  • * @return void
  • */
  •  public function down()
  •  {
  •  //
  •  }
  • }

  • As you can see, our migration class consists of two methods, up() is responsible for making all of your database changes, where down() accomplishes the exact reverse, this way a migration can be performed, and rolled back when necessary. If you were to create a table within the up() method, we would DROP the same table in the down() method. So how do we perform changes on our database, no doubt with some complex ugly SQL query right? Haha, no. We are using Laravel, if it's ugly, it's not in the framework. Lets have a look at creating a table with the Laravel Schema class.

  • <?php
  • Schema::create('users', function($table) {
  •  // auto incremental id (PK)
  • $table->increments('id');
  •  // varchar 32
  • $table->string('username', 32);
  • $table->string('email', 320);
  • $table->string('password', 64);
  •  // int
  • $table->integer('role');
  •  // boolean
  • $table->boolean('active');
  •  // created_at | updated_at DATETIME
  • $table->timestamps();
  • });
  • We call the create() method on the Schema class to create a new table, as parameters we pass the name of the table to be created, and a closure as the second parameter. We also need to pass a parameter to the closure, you can call it whatever you like, but I like using $table because I think it makes the code read better.
    (fc_lamp:此相当于用SQL创建表。) 

    Inside the closure, we can use the $table parameter to create our fields with a number of handy, well-named methods, lets take a quick look at them.(fc_lamp:有如下可选的字段类型)

    increments()

    Add an auto-incrementing ID to the table, most of your tables will have this!

    string()

    Create a VARCHAR field, string sounds a lot better doesn't it?

    integer()

    Add an integer field to the table.

    float()

    Add a float field to the table.

    boolean()

    Add a boolean field to the table.

    date()

    Add a date field to the table.

    timestamp()

    Add a timestamp field to the table.

    timestamps()

    Add created_at updated_at timestamp fields.

    text()

    Add a text field to the table.

    blob()

    Add a blob data field to the table.

    You can also use the chainable method ->nullable() to allow the field to receive NULL values.

    Full details on the parameters available to the above methods can be found in the official documentation.

    Great, so now we have created our table! Since we created the table in the up() method, we now need to DROP the table in the down() method, so that the schema would return to its original form after a rollback. Fortunately the Schema class has another method that is perfect for this task.

    1. <?php
    2. Schema::drop('users');

    Yep, it doesn't get easier than that. The Schema class also has functions for performing other schema tasks, such as dropping columns drop_column(), adding indexes unique() and a number of foreign key methods. I think that covering all of them here would turn the book into an API, something I don't wish to do, besides they are explained well in the official documentation, and if you take a look there we can move on to new things, how about finding out how we run these migrations? Let's do it!

    Before we can run our migrations, we need to install the laravel_migrations table, so that Laravel can keep track of which migrations have been run. Fortunately artisan has a command which will perform the necessary database changes for you, let's have a go.

    1. php artisan migrate:install (fc_lamp:创建迁移表)

    And the result..

    1. Migration table created successfully.

    Great! Now the laravel_migrations table has been created, we can finally run our new migration. Simply use the task name this time, here we go.

    1. php artisan migrate (fc_lamp:执行迁移动作)
    2. Migrated: application/2012_03_30_220459_create_users

    Woop, if we take a look at our database the users table has been created successfully. Wait, we made a mistake! (we didn't, but I like drama and I need an excuse to use rollback) Let's rollback our schema to redo the changes.

    1. php artisan migrate:rollback
    2. Rolled back: application/2012_03_30_220459_create_users

    Please note that if you would like to provide example data to populate your database with, simply create it with the Fluent Query Builder, however a guide on this topic will not appear until the next chapter, so you might want to wait a day or so!

    Easy as pie! Now you know how to use migrations, you can build your schema and populate your database whenever you please! Next chapter we will be looking at the Fluent Query Builder.








      评论这张
     
    阅读(690)| 评论(0)
    推荐 转载

    历史上的今天

    在LOFTER的更多文章

    评论

    <#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
     
     
     
     
     
     
     
     
     
     
     
     
     
     

    页脚

    网易公司版权所有 ©1997-2017