Laravel 5.4 field doesn't have a default value

此生再无相见时 提交于 2019-12-20 17:31:44

问题


I am having this error and none of the googled result i checked is similar to my problem.

I have an application with class Deal, User, and Matches

A deal has many matches. A user has many matches. A user has many deals.

I am attempting to create a new Match using my Deal object

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

This is my match class, i have defined all needed relationships

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');
    }
}

And i keep getting this error when i attempt to create a new match.

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))

I have my guarded to be an empty array, what could be the problem?


回答1:


Remove the guarded array and add the fillable instead:

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



回答2:


If you would like to revert to previous behavior, update your

config/database.php

file and set 'strict' => false for your connection.




回答3:


Since it was a unique field in my case, I could not make it nullable.

For me, I had an empty constructor which was causing the issue don't know why. Please comment if anyone knows the reason.

public function __construct(){

}

Commenting/removing it resolved the issue.




回答4:


Alexey Mezenin's Answer is correct and a good one.

Another way i used around it, for those who want to maintain the guarded empty array is to create a new Match object and put in the attributes and save.

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


来源:https://stackoverflow.com/questions/43186521/laravel-5-4-field-doesnt-have-a-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!