

下記のエラーを解決したいのですがなかなかできずに困っています。  
中間テーブルにgatya_idとusers_idを保存したいのですが下記のエラーが出るという状況です。  
外部キーの部分で何か問題があるというのはわかるのですが、どこが問題かわかりません。

[code]

    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))'
    
[/code]

[code]

        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();
            });
        }
    
[/code]

[code]

        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();
            });
        }
    
[/code]

[code]

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateUserGatyaTable extends 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');
        }
    }
    
    
[/code]

[code]

    <?php
    
    namespace App;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    
        /**
         * The attributes that are mass 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();
        }
    }
    
    
[/code]

[code]

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    
    class Gatya extends 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;
        }
    
    
    }
    
    
[/code]

下記のdrawメソッドが中間テーブルにデータを保存するメソッド（のつもり）です。  
どなたかご教授いただけると幸いです。

[code]

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


CC BY-SA 4.0
2021-05-06T17:18:15.730
75707
2023-10-17T04:10:16.223
2021-05-07T01:11:08.343
3060
44107
question
sql laravel
'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails〜を解決したい


同じ内容のエラーにハマり、解消できました。  
belongsToManyの第3引数と第4引数を入れ替えてみてください。

[Laravel 8.x Eloquent:リレーション](https://readouble.com/laravel/8.x/ja/eloquent-
relationships.html?header=%25E3%2583%25A2%25E3%2583%2587%25E3%2583%25AB%25E6%25A7%258B%25E9%2580%25A0)

> ３番目の引数は、関係を定義しているモデルの外部キー名であり、４番目の引数は、関連付けるモデルの外部キー名です。

こちら（Qiita）にもまとめられていました。  
[Laravelのリレーションがわかりづら過ぎるので忘備録](https://qiita.com/yosida001/items/09cc6e3f6afad5bcad35)

以下、修正案です。

[code]

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    
    class Gatya extends Model
    {
        // 略
    
        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();
        }
    
        // 略
    
    }
    
[/code]

解消できたら、Userのgatya()に関しても同様に修正すべきかと思われます。

※追記  
多対多のリレーションが一つであればLaravel側がうまく処理してくれるので以下の修正がシンプルで望ましいかもしれません。

[code]

    return $this->belongsToMany(User::class)->withTimestamps();
    
[/code]


CC BY-SA 4.0
2021-09-03T09:37:39.210
82210
2021-09-03T10:08:18.573
2021-09-03T10:08:18.573
48041
48041
75707
answer