2017-04-03 121 views
5

我有這個錯誤,並且沒有檢查到的搜索結果與我的問題類似。Laravel 5.4字段沒有默認值

我有類交易,用戶的應用程序,並匹配

協約有很多比賽。 用戶有很多匹配項。 用戶有很多交易。

我試圖用

$deal->matches()->create(['user_id'=>$id]); 

這是我的比賽類,我已經定義了所有需要的關係

class Match extends Model 
{ 
    /** 
    * The attributes that are mass assignable. 
    * 
    * @var array 
    */ 
    protected $guarded = []; 
    public $timestamps = false; 
    public $expired_on = ""; 


    public static function boot() 
    { 
     parent::boot(); 

     static::creating(function ($model) { 
      $model->matched_on = $model->freshTimestamp(); 
     }); 
    } 

    public function __construct(){ 
     $d = (new \DateTime($this->matched_on))->modify('+1 day'); 
     $this->expired_on = $d->format('Y-m-d H:i:s'); 
    } 


    /** 
    * Get the user that owns the match. 
    */ 
    public function user() 
    { 
     return $this->belongsTo('App\User'); 
    } 

    /** 
    * Get the deal that owns the match. 
    */ 
    public function deal() 
    { 
     return $this->belongsTo('App\Deal'); 
    } 
} 

我的交易對象來創建一個新的比賽,我不斷收到此錯誤,當我試圖創建一個新的比賽。

QueryException in Connection.php line 647: SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into matches (deal_id) values (1))

我有我的看守是一個空陣列,可能是什麼問題?

+0

我沒有得到的是爲什麼匹配如果它是數據透視表有一個模型類https://laravel.com/docs/5.0/eloquent#working-with-pivot-tables – Indra

+0

這通常是當你不喜歡不插入某個不能爲NULL或沒有默認值的字段。所以你的'user_id'不會被插入 – Cr1xus

+0

@ Cr1xus,是的,我的'user_id'沒有被插入,現在我的問題是爲什麼它是這樣,看到我在我的創建方法。 –

回答

9

取出guarded陣列,並添加fillable代替:

protected $fillable = ['user_id', 'deal_id']; 
+1

會這樣做,但根據文檔 –

1

阿列克謝Mezenin的答案是正確的,一個好。

另一種我用它的方式,對於那些想要維護守護空數組的人來說,是創建一個新的Match對象並放入屬性並保存。

  $match->user_id = $id; 
      $match->deal_id = $deal->id; 
      $match->matched_on = $match->freshTimestamp(); 
      $match->save(); 
7

如果你想恢復到以前的行爲,請更新您

config/database.php

文件,並設置'strict' => false爲您的連接。

+0

使用_guarded_沒有問題您是否需要運行任何工匠清除命令,或在此之後進行刷新遷移? – blamb

+1

在Laravel 5.5中使用新的命令php的工匠遷移:新鮮 - 種子和玩得開心:) – grantDEV

+1

謝謝。那麼,你說這確實需要重新運行遷移呢?對於記錄,我認爲這是'php工匠遷移:刷新 - 種子'。除非有新鮮的我不知道。 ;-) – blamb