【laravel避坑筆記】laravel報(bào)錯(cuò)的問(wèn)題42S01 420004 42S22]等…

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

下面由laravel教程欄目給大家介紹laravel報(bào)錯(cuò)的問(wèn)題42S01 420004 42S22]等…?希望對(duì)需要的朋友有所幫助!

laravel避坑筆記

來(lái)源網(wǎng)絡(luò)

1.Laravel 5.4: Specified key was too long error

原因:從LV 5.4起數(shù)據(jù)庫(kù)默認(rèn)字符集為utf8mb4(包括了對(duì) emojis 的支持)。如果使用的是 MySQL v5.7.7 或更高版本不需要做什么修改。使用更早版本的MySQL數(shù)據(jù)庫(kù)(包括MariaDB)的童鞋可以這樣修改了,修改文件 /project/app/Providers/AppServiceProvider.php

use IlluminateSupportFacadesSchema; // 注意要引入命名空間   public function boot()     {         Schema::defaultStringLength(191); // 針對(duì) 早期 mysql 數(shù)據(jù)遷移     }

再重新使用遷移命令:

php artisan migrate

2.SQLSTATE[42S01]: Base table or view already exists: 1050

遷移數(shù)據(jù)時(shí)表已存在,

解決辦法:

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

3.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,  ],

設(shè)置可為空的時(shí)間戳:

$table->nullableTimestamps()

設(shè)置默認(rèn)時(shí)間戳

$table->timestamps('created_at');// 會(huì)生成created_atupdated_at字段

4.PDOException::(“SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘created_at’ in ‘field list’”)

此問(wèn)題是由于 table 遷移時(shí)沒(méi)有設(shè)置默認(rèn)時(shí)間戳字段,但使用的是 factory 方法 生成 seed 數(shù)據(jù),可以修改

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

重復(fù)make:migration

確切來(lái)說(shuō),這個(gè)也不算是坑,因?yàn)檫@個(gè)操作本身就是只需執(zhí)行一次

但對(duì)于新手來(lái)說(shuō),可能無(wú)意間就重復(fù)執(zhí)行多次,而 make:migration 時(shí)是不會(huì)報(bào)錯(cuò)的;
而在執(zhí)行遷移時(shí)問(wèn)題就來(lái)了:

【laravel避坑筆記】laravel報(bào)錯(cuò)的問(wèn)題42S01 420004 42S22]等…

解決辦法就是刪除或修改同一 table 的 schema 名稱。
【laravel避坑筆記】laravel報(bào)錯(cuò)的問(wèn)題42S01 420004 42S22]等…

5.php artisan db:seed 表名變復(fù)數(shù) 單數(shù)

這可能和 Chinglish 有關(guān),老外習(xí)慣把表名寫為復(fù)數(shù),所以干脆默認(rèn)Model 對(duì)應(yīng)的表名是這個(gè)英文單詞的復(fù)數(shù)形式
因此,要在 model 里重寫 $table 屬性,如:

protected $table=’student’;

查找于網(wǎng)絡(luò),儲(chǔ)存方便自己方便他人

以上就是【

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊8 分享
站長(zhǎng)的頭像-小浪學(xué)習(xí)網(wǎng)月度會(huì)員