私はこのエラーに悩まされており、グーグルで調べた結果はどれも私の問題と同様ではありませんでした。
Dealクラス、Userクラス、Matchesクラスを持つアプリケーションを作成しました。
案件には多くのマッチがあります。 ユーザは多くのマッチを持ちます。 ユーザが多くの案件を持つ。
ディールオブジェクトを使用して新しいマッチを作成しようとしています。
$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]:一般的なエラーです。1364 Field 'user_id' doesn't have a default value (SQL: insert into
matches
(deal_id
) values (1)).
私は私のガードが空の配列になるように持っている、何が問題なのでしょうか?
guarded配列を削除し、代わりに
fillable` を追加します。
protected $fillable = ['user_id', 'deal_id'];
私の場合はユニークなフィールドだったので、無効にすることはできませんでした。
私にとって、問題を引き起こしている空のコンストラクターがいた理由はわかりません。 理由がわかっている場合はコメントしてください。
public function __construct(){
}
コメント/削除すると問題が解決しました。