SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(Laravel)

时间:2019-04-10 06:57:45

标签: mysql laravel-5

如何解决此错误。

  

SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(kindmill_dbdevice_tokens,CONSTRAINT device_tokens_user_id_foreign外键({{ 1}})在删除级联上的引用user_idusers)(SQL:插入iddevice_tokensdeviceTokenupdated_at)值(dqq37149351b3710139155ba81241dc20a5641961d324d9612ab293a41d322415,2019-04-10 06:35:31,2019-04-10 06:35:31))

我不知道为什么向我显示此错误,但我无法解决此错误。这是我的代码。请帮忙。 这是数据库迁移

created_at

这是我的控制器代码

class CreateDeviceTokensTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('device_tokens', function (Blueprint $table) {
        $table->bigInteger('id', true)->unsigned();
        $table->bigInteger('user_id')->unsigned()->index('user_id');
        $table->string('deviceToken');
        $table->timestamps();

        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('device_tokens');
}
}

1 个答案:

答案 0 :(得分:0)

在模型DeviceToken.php中,我在受保护的$ fillable变量中添加了user_id

可以解决此错误。

这是模型的代码:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class DeviceToken extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id', 'deviceToken',
    ];

    /**
     * Get the user that owns the token.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}