Joh*_*vid 18 php mysql laravel laravel-5.4
我有这个错误,我检查的google搜索结果都没有类似于我的问题.
我有一个类Deal,User和Matches的应用程序
一笔交易有很多比赛.用户有很多匹配.用户有很多优惠.
我正在尝试使用我的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:insert into
matches(deal_id)values(1))
我保护自己是一个空阵,可能是什么问题?
Ale*_*nin 54
删除guarded数组并添加fillable相反:
protected $fillable = ['user_id', 'deal_id'];
gra*_*DEV 24
如果您想恢复以前的行为,请更新您的
配置/ database.php中
文件并设置'strict' => false为您的连接.
由于在我的情况下它是一个独特的字段,因此我无法将其设为可空。
对我来说,我有一个空的构造函数,它导致了这个问题,不知道为什么。如果有人知道原因,请发表评论。
public function __construct(){
}
评论/删除它解决了这个问题。
如果您的模型中有一个构造函数,只需确保它也调用了父构造函数:
public function __construct( array $attributes = array() ) {
    // mandatory
    parent::__construct($attributes);
    //..
}
否则,它会破坏某些功能,例如Model::create.
我使用 Laravel 8 并通过以下两个步骤修复了此错误:
在用户模式下将单词从$guarded一个数组移动到另一个数组$fillable
Config.database.php:  'strict' => false在数组中'mysql'
Alexey Mezenin 的回答是正确且很好的。
我使用的另一种方法是,对于那些想要维护受保护的空数组的人来说,创建一个新的 Match 对象并放入属性并保存。
            $match->user_id = $id;
            $match->deal_id = $deal->id;
            $match->matched_on = $match->freshTimestamp();
            $match->save();
| 归档时间: | 
 | 
| 查看次数: | 56835 次 | 
| 最近记录: |