學習 Laravel 那些坑(二)資料移轉

來源:互聯網
上載者:User

目錄:

Laravel 5.4: Specified key was too long error SQLSTATE[42S01]: Base table or view already exists: 1050 PDOException::(“SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for ‘published_at’”) 設定可為空白的時間戳記: 設定預設時間戳記 PDOException::(“SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘field list’”) 重複make:migration php artisan db:seed 表名變複數 單數

Laravel 5.4: Specified key was too long error

原因:從LV 5.4起資料庫預設字元集為utf8mb4(包括了對 emojis 的支援)。如果使用的是 MySQL v5.7.7 或更高版本不需要做什麼修改。

使用更早版本的MySQL資料庫(包括MariaDB)的童鞋可以這樣修改了,修改檔案 /project/app/Providers/AppServiceProvider.php

use Illuminate\Support\Facades\Schema; // 注意要引入命名空間 public function boot()    {        Schema::defaultStringLength(191); // 針對 早期 mysql 資料移轉    }

再重新使用遷移命令:

php artisan migrate
SQLSTATE[42S01]: Base table or view already exists: 1050

遷移資料時表已存在,

解決辦法:

刪除已存在的表,然後重新遷移。

遷移結果如下:
PDOException::(“SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for ‘published_at’”)

修改方法一:vim config/database.php

'mysql' => [     'driver' => 'mysql',.... ...     'prefix' => '',      'strict' => true, // 修改這裡     'engine' => null, ],  

修改為:

'mysql' => [     'driver' => 'mysql',.... ...     'prefix' => '',      'strict' => false, // 修改這裡     'engine' => null, ],  
設定可為空白的時間戳記:
$table->nullableTimestamps() 
設定預設時間戳記
$table->timestamps('created_at');// 會產生created_at\updated_at欄位
PDOException::(“SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘field list’”)

此問題是由於 table 遷移時沒有設定預設時間戳記欄位,但使用的是 factory 方法 產生 seed 資料,可以修改

public function up()    {         Schema::create('posts', function (Blueprint $table) {      $table->increments('id');      $table->string('slug')->unique();      $table->string('title');      $table->text('content');      $table->timestamps(); // 添加這行      }); }   
重複make:migration

確切來說,這個也不算是坑,因為這個操作本身就是只需執行一次

但對於新手來說,可能無意間就重複執行多次,而 make:migration 時是不會報錯的;
而在執行遷移時問題就來了:

解決辦法就是刪除或修改同一 table 的 schema 名稱。
php artisan db:seed 表名變複數 單數

這可能和 Chinglish 有關,老外習慣把表名寫為複數,所以乾脆預設Model 對應的表名是這個英文單詞的複數形式
因此,要在 model 裡重寫 $table 屬性,如:

protected $table='student';

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.