Laravel5.1 設定資料庫和Migration

來源:互聯網
上載者:User

標籤:schema   oar   mina   更改   san   pass   print   執行命令   目錄   

在laravel中 我們可以在項目根目錄的.env檔案中更改我們的配置。

開啟.env檔案後找到DB為首碼的幾個欄位,來更改我們的配置,如果想做更多的配置 可以到\config\database.php中修改。

配置好後我們來初始化資料庫,使用laravel內建的遷移來產生user和password表:

php artisan migrate

執行此命令後會探索資料庫多了user和password表,這樣我們的資料庫就配置好了。

 

資料庫遷移--migrations

migration是資料庫遷移,也可稱作為版本控制,這樣別人下載你的源碼 有了這些migration檔案 只需要執行php artisan migrate命令就可以產生所有的表,這樣很方便。

 

建立遷移檔案
php artisan make:migration create_articles_table --create=articles 

我們建立的migration檔案命名應該要明確,後面的--create=articles   聲明了要建立一張articles表。

 

在\database\migrations\中我們可以看到我們剛剛建立的migration檔案:

class CreateArticlesTable extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create(‘articles‘, function (Blueprint $table) {            $table->increments(‘id‘);            $table->timestamps();        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::drop(‘articles‘);    }}

其中有兩個方法:up和down,up沒什麼好說的,就是執行migrate命令時要裝載的欄位,down就是復原時要做什麼操作。

執行命令:

php artisan migrate

開啟表後。。。哎呀。。忘了加欄位了,此時我們可以建立這麼一個migration:

php artisan make:migration insert_content_to_articles --table=articles

此時的 --table=articles  是說明 我們要對articles這張表做些修改,編輯這個migration:

<?phpuse Illuminate\Database\Schema\Blueprint;use Illuminate\Database\Migrations\Migration;class InsertContentToArticles extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::table(‘articles‘, function (Blueprint $table) {            // 添加我們想要的欄位            $table->string(‘content‘);        });    }    /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::table(‘articles‘, function (Blueprint $table) {            // 對應的復原操作            $table->dropColumn(‘content‘);        });    }}

執行migrate操作來看看操作是否成功了吧。

 

復原操作

復原上一次的遷移:

php artisan migrate:rollback

復原所有的遷移:

php artisan migrate:reset

 

Laravel5.1 設定資料庫和Migration

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.