简体   繁体   中英

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails(Laravel)

How to resolve this error.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( kindmill_db . device_tokens , CONSTRAINT device_tokens_user_id_foreign FOREIGN KEY ( user_id ) REFERENCES users ( id ) ON DELETE CASCADE) (SQL: insert into device_tokens ( deviceToken , updated_at , created_at ) values (dqq37149351b3710139155ba81241dc20a5641961d324d9612ab293a41d322415, 2019-04-10 06:35:31, 2019-04-10 06:35:31))

I don't know why show me this error i can not resolve this error. Here is My code. Please help. here is database migration

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');
}
}

Here is my controller code

public function deviceToken(UpdateDeviceToken $request)
{
    $user = JWTAuth::parseToken()->toUser();

    // $deviceToken = DeviceToken::where('deviceToken', $deviceToken)->count();
    // if($deviceToken == 0)
    // {   
    //     $user = $user->deviceTokens()->create(){
    //         'deviceToken' = $request->input('deviceToken');
    //     }   
    // } else {

    // }

    $deviceToken = DeviceToken::updateOrCreate([
        'deviceToken' => $request->input('deviceToken'), 
    ],
    [
        'user_id' => $user->id,
        'deviceToken' => $request->input('deviceToken'),
    ]);
    return $user;
}

In My model DeviceToken.php I added the user_id in the protected $fillable variable.

That resolves this error.

Here is the code of model:

<?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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM