Laravel 5.4字段没有默认值

时间:2017-04-03 13:53:32

标签: php mysql laravel laravel-5.4

我遇到了这个错误,我检查的google搜索结果都与我的问题类似。

我有一个使用“交易”,“用户”和“匹配”类的应用程序

交易有很多比赛。 用户有很多匹配。 用户有很多优惠。

我正在尝试使用我的Deal对象

创建一个新的Match
$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');
    }
}

当我尝试创建新匹配时,我一直收到此错误。

  

Connection.php第647行中的QueryException:   SQLSTATE [HY000]:常规错误:1364字段'user_id'没有默认值(SQL:插入matchesdeal_id)值(1))

我保护自己是一个空阵列,可能是什么问题?

9 个答案:

答案 0 :(得分:38)

删除guarded数组,然后添加fillable

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

答案 1 :(得分:22)

如果您想恢复以前的行为,请更新您的

  

配置/ database.php中

文件并为您的连接设置'strict' => false

答案 2 :(得分:5)

如果您的模型中有一个构造函数,只需确保它也调用了父构造函数即可:

public function __construct( array $attributes = array() ) {
    // mandatory
    parent::__construct($attributes);

    //..
}

否则,它将破坏某些功能,例如Model::create

答案 3 :(得分:3)

Alexey Mezenin 答案是正确的,也是一个好的答案。

我使用它的另一种方式,对于那些想要维护受保护的空数组的人来说,就是创建一个新的Match对象并放入属性并保存。

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

答案 4 :(得分:3)

因为在我的情况下这是一个唯一字段,所以我无法将其设置为空。

对我来说,我有一个空的构造函数,导致问题不知道为什么。 如果有人知道原因,请发表评论。

public function __construct(){

}

评论/删除它可以解决问题。

答案 5 :(得分:1)

解决此错误的另一种方法是

'strict'=>否,

放入mysql数组中的config / database.php

答案 6 :(得分:0)

我正在使用Laravel 8,并通过以下两个步骤解决了该错误:

  1. 在用户模式下将单词从$guarded数组移到$fillable数组

  2. Config.database.php:'strict' => false数组中的'mysql'

答案 7 :(得分:0)

手动导入/导出数据库时,请检查所有表设置的传输是否成功。如果您忘记添加自增主键,Laravel 不会为您填充该值。

之后添加 AUTO_INCREMENT 将解决问题。

答案 8 :(得分:0)

我有这个错误,但我的错误是制作类模型:

$book = new Book();

虽然这是真的

$book = new Book($request->all());