2016-12-11 94 views
0

當我嘗試保存到數據庫中,我不斷收到在我的控制器這些錯誤Laravel數據保存到數據庫模型SQLSTATE [23000]:完整性約束違規:19 NOT NULL約束失敗:

PDOException in Connection.php line 479: 
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: images.uploader 


QueryException in Connection.php line 769: 
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: images.uploader (SQL: insert into "images" ("name", "description", "updated_at", "created_at") values (coat, description test, 2016-12-11 10:34:34, 2016-12-11 10:34:34)) 

的存儲功能

public function store($name) 
{ 
    $image = new Image; 
    $image->name = $name; 
    $image->description = "description test"; 

    $image->save(); 

} 

遷移

public function up() 
{ 
    Schema::create('images', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('uploader'); 
     $table->string('name'); 
     $table->string('description'); 
     $table->integer('width'); 
     $table->integer('height'); 
     $table->decimal('size'); 
     $table->integer('views')->default(0); 
     $table->string('extension'); 
     $table->timestamps(); 
    }); 
} 

和我的模型

class Image extends Model 
{ 
    protected $fillable = ["name", "description"]; 
} 

我不知道我在做什麼錯,我一直卡住這個太長。 我希望有人可以幫我

回答

1

錯誤消息告訴你,欄uploader不應該是NULL

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: images.uploader 

遷移更改爲

$table->string('uploader')->default(''); 

OR

$table->string('uploader')->nullable(); 

或者,你可以使用mutators,把這個在您的Image模型。

public function setUploaderAttribute($value) 
{ 
    $this->attributes['uploader'] = (is_null($value) ? '': $value); 
} 
+0

我看到所以我不填充的每一列都需要爲空或者有一個空字符串的默認值 是對的嗎? –

+0

是的,基本上這些限制是爲了確保你的數據庫中有正確的數據。所以,如果你期望它是空的,你應該說明它 – SteD

+0

好的,謝謝你的幫助^ _ ^ –

相關問題