2017-04-03 120 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