首頁  >  文章  >  後端開發  >  laravel 資料遷移問題

laravel 資料遷移問題

WBOY
WBOY原創
2016-12-01 00:25:441037瀏覽

使用資料遷移創建了一個表,表裡已經有資料了,這個時候想要添加字段,或修改字段,或刪除字段,要怎麼操作?

回覆內容:

使用資料遷移創建了一個表,表裡已經有資料了,這個時候想要添加字段,或修改字段,或刪除字段,要怎麼操作?

重新建立migration文件,通常我們建立的migration文件有兩種,一種是創建表,另一種是修改表,比如說你要創建一個表,打個比方你要創建users表,你會這麼寫:

<code class="bash">php artisan make:migration create_users_table --create=users</code>

如果你已經執行了php artisan migrate, 並且已經插入了一些數據,這時候你如果想修改,添加或者刪除當中的字段,那麼你需要重新建立一個migration文件,打個比方,你現在要添加個email欄位

<code class="bash">php artisan make:migration add_email_column_to_users_table --table=users</code>

將你要的內容寫在add_email_column_to_users_table檔中,然後在執行 php artisan migrate

至於migration文件中的內容的寫法都一樣,文檔中非常清楚的寫著,或者你也可以看下我這篇教程:

http://www.zhoujiping.com/scratch/fetching-data.html

另外你看下資料庫中的migraitons表中的記錄,你應該會想通你之前出錯的原因

添加字段

<code>Schema::table('users', function ($table) {
    $table->string('email');
});</code>

修改字段

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

重命名字段

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

移除欄位

<code>Schema::table('users', function ($table) {
    $table->dropColumn('votes');
});</code>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn