php - Laravel 5.4 字段没有默认值

标签 php mysql laravel laravel-5.4

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

我有一个包含 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');
    }
}

当我尝试创建新匹配项时,我不断收到此错误。

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

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

最佳答案

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

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

关于php - Laravel 5.4 字段没有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186521/

相关文章:

php - 如何在 Springboard 上为 Safari Mobile 网站创建图标?

php - mysql子句有什么问题

php - $_POST 复选框数组仅返回单个值

mysql - 如何在 Laravel 中转换我的 MySql 查询

php - laravel中登录用户的查询结果

php - 当 Laravel 队列 :listen times out 时获取当前正在运行的任务

PHP - Paypal API 表单和安全性

mysql - 仅列出与另一个特定属性的所有其他记录链接的特定属性的记录

java - Android 网络服务 PHP MYSQL

laravel - 从集合创建集合?