Laravel 5.4 字段没有默认值

新手上路,请多包涵

我遇到了这个错误,我检查的谷歌搜索结果都没有与我的问题相似。

我有一个包含 Deal、User 和 Matches 类的应用程序

一笔交易有很多匹配项。一个用户有很多匹配项。一个用户有很多交易。

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

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

我有我的守卫是一个空数组,可能是什么问题?

原文由 John David 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 806
2 个回答

删除 guarded 数组并添加 fillable 代替:

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

原文由 Alexey Mezenin 发布,翻译遵循 CC BY-SA 3.0 许可协议

更改您的“config/database.php”将无济于事。如果您收到此错误,则说明您没有将数据正确发送到数据库。检查控制器中的函数,create() 方法可能被 if 语句或其他内容阻塞。或者

如果它是 API,请检查来自您问题所在的前端的发布请求。确保表单正确传递给请求。

原文由 Real-Artisan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题