如何修复使用关联方法更新属于"Field {$foreign_key} doesn't have a default value"关系时出错



我已经在模型和Match模型TokenMatch的两个模型之间创建了"一对一"的雄辩关系,但是当我尝试将TokenMatch与匹配相关联时,我遇到了一个错误:

"Field 'tokenmatch_id' doesn't have a default value (SQL: insert into `matches` (`id`, `updated_at`, `created_at`) values (, 2019-04-22 08:55:51, 2019-04-22 08:55:51))
"

我的代码问题:

$match = new Match();
$tokenmatch = TokenMatch::find(1);
$match->token()->associate($tokenmatch)->save();

类匹配

class Match extends Model
{
    public function token()
    {
         return $this->belongsTo('AppTokenMatch' , 'id', 'tokenmatch_id');
    }
}

类令牌匹配

class TokenMatch extends Model
{
    protected  $table = 'tokensmatch';
    public function match()
    {
        return $this->hasOne('AppMatch','tokenmatch_id');
    }
}

匹配表

 Schema::create('matches', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->boolean('isFinished')->nullable();
            $table->boolean('isWon')->nullable();
            $table->unsignedBigInteger('tokenmatch_id');
            $table->foreign('tokenmatch_id')->references('id')->on('tokensmatch');
            $table->timestamp('created_at')->default(IlluminateSupportFacadesDB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(IlluminateSupportFacadesDB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
        });

令牌匹配表

 Schema::create('tokensmatch', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->boolean('isUsed')->default(false);
            $table->string('token', 15)->unique();
            $table->dateTimeTz('expiryDate')->nullable();
            $table->boolean('isValid')->default(true);
        });

所以我期望当我保存新的模型匹配时,在表的"tokenmatch_id"字段上匹配不为空

...
$match->token()->associate($tokenmatch)->save();
...

我认为您在模型中定义的关系存在问题Match。它应该是:

public function token()
{
     return $this->belongsTo('AppTokenMatch' ,'tokenmatch_id', 'id');
}

请参考:

https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse

更改

$table->unsignedBigInteger('tokenmatch_id');

$table->unsignedBigInteger('tokenmatch_id')->nullable();

最新更新