Laravel 5.4字段没有默认值

Joh*_*vid 18 php mysql laravel laravel-5.4

我有这个错误,我检查的google搜索结果都没有类似于我的问题.

我有一个类Deal,User和Matches的应用程序

一笔交易有很多比赛.用户有很多匹配.用户有很多优惠.

我正在尝试使用我的Deal对象创建一个新的Match

$deal->matches()->create(['user_id'=>$id]);
Run Code Online (Sandbox Code Playgroud)

这是我的匹配类,我已经定义了所有需要的关系

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试创建一个新的匹配时,我不断收到此错误.

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

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

Ale*_*nin 54

删除guarded数组并添加fillable相反:

protected $fillable = ['user_id', 'deal_id'];
Run Code Online (Sandbox Code Playgroud)

  • 可以这样做,但是根据文档使用_guarded_没什么错 (2认同)

gra*_*DEV 24

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

配置/ database.php中

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

  • 谢谢。那么,您说它确实需要重新运行迁移吗?为了记录,我认为这是`php artisan migrate:refresh --seed`。除非有新鲜的我不知道。;-) (2认同)
  • 是的,我这样做了,它起作用了, migrate:fresh 是新命令,看看 https://laravel-news.com/laravel-5-5 (2认同)

viv*_*ani 9

由于在我的情况下它是一个独特的字段,因此我无法将其设为可空。

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

public function __construct(){

}
Run Code Online (Sandbox Code Playgroud)

评论/删除它解决了这个问题。

  • 可以确认这是一回事。我也刚碰到它。我删除了空的构造函数类,“字段没有默认值”错误消失了。 (2认同)
  • 确认的。需要调用父构造函数!并传递属性:/sf/answers/4190630671/ (2认同)

dav*_*e44 8

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

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

    //..
}
Run Code Online (Sandbox Code Playgroud)

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


W K*_*nny 7

我使用 Laravel 8 并通过以下两个步骤修复了此错误:

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

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


Joh*_*vid 5

Alexey Mezenin 的回答是正确且很好的。

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

            $match->user_id = $id;
            $match->deal_id = $deal->id;
            $match->matched_on = $match->freshTimestamp();
            $match->save();
Run Code Online (Sandbox Code Playgroud)


小智 5

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

'严格' => 假,

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