I want to resolve 'SQLSTATE [23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails~

Asked 1 years ago, Updated 1 years ago, 344 views

I would like to resolve the error below, but I am having a hard time getting it.
I would like to save the gatya_id and users_id in the middle table, but the following error appears.
I understand that there is something wrong with the foreign key, but I don't know where the problem is.

Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laravel_local`.`user_gatya`, CONSTRAINT `user_gatya_users_id_foreign` FOREIGN KEY (`users_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `user_gatya` (`created_at`, `gatya_id`, `updated_at`, `users_id`) values(2021-05-06 17:01:28,1,2021-05-06 17:01:28,5)'
public function up()
    {
        Schema::create('users', function(Blueprint$table){
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email') ->unique();
            $table->timestamp('email_verified_at') ->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
public function up()
    {
        Schema::create('gatya', function(Blueprint$table){
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('description');
            $table->string ('rarity');
            $table->string('img');
            $table->timestamps();
        });
    }
<?php

use Illuminate\Database\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserGatyaTable extensions Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_gatya', function(Blueprint$table){
            $table->bigInteger('users_id')->nullable()->unsigned();
            $table->foreign('users_id')->references('id')->on('users')->onDelete('cascade');
            $table->bigInteger('gatya_id')->nullable()->unsigned();
            $table->foreign('gatya_id')->references('id')->on('gatya')->onDelete('cascade');
            $table->timestamps();
        });
    }

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

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notify;

class User extensions Authenticatable
{
    use Notify;

    /**
     * The attributes that are pass assignable.
     *
     * @var array
     */
    protected$fillable=[
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected$casts=[
        'email_verified_at' = > 'datetime',
    ];

    public function gatya(){
        return$this->belongsToMany('App\Gatya', 'user_gatya', 'gatya_id', 'users_id') ->withTimestamps();
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Gattya extensions Model
{
    //
    protected$table='gatya';
    
    protected$fillable=[
        'title',
        'description',
        'rarity',
        'img'
    ];

    public function cards(): BelongsToMany
    {
        return$this->belongsToMany('App\User', 'user_gatya', 'users_id', 'gatya_id', )->withTimestamps();
    }

    public function getCountCardsAttribute(): int
    {
        return$this->user_gatya->count();
    }

    public function isCardHave(?User$user):bool
    {
        return$user
        ? (bool)$this->cards->where('id', $user->id)->get()
        : false;
    }


}

The draw method below is the method that stores data in the intermediate table.
I would appreciate it if someone could tell me.

public function draw()
    {
      $card=Gatya::inRandomOrder()->first();
      $card->cards()->attach(User::find(1));
      return$card;
    }

sql laravel

2022-09-30 21:56

1 Answers

I fell in love with the same error and was able to resolve it.
Try replacing the third and fourth arguments of belongsToMany

Larvel 8.x Eloquent:Relationship

The third argument is the foreign key name of the model that defines the relationship, and the fourth argument is the foreign key name of the model that you want to associate.

It was also summarized here (Qiita).
Forgetting Ravel Relationships

The following is an amendment.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Gattya extensions Model
{
    // approximately

    public function cards(): BelongsToMany
    {
        // return$this->belongsToMany('App\User', 'user_gatya', 'users_id', 'gatya_id', )->withTimestamps();
        return$this->belongsToMany('App\User', 'user_gatya', 'gatya_id', 'users_id') ->withTimestamps();
    }

    // approximately

}

Once resolved, I think we should fix the user's gatya() as well.

追Additional
If there is one many-to-many relationship, Ravel will handle it well, so the following modifications may be simple and desirable.

return$this->belongsToMany (User::class)->withTimestamps();


2022-09-30 21:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.