1452无法添加或更新子行:外键约束失败Laravel 5.4

时间:2017-06-07 14:25:36

标签: php mysql laravel

我有两张桌子:

1)用户

Schema::create('users', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->string('id')->unique();
            $table->string('name')->nullable();
            $table->string('surname')->nullable();
            $table->string('email')->unique()->nullable();
            $table->string('address')->nullable();
            $table->string('telephone')->nullable();
            $table->timestamps();
        });

2)users_games

  Schema::create('user_games', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->increments('id');
            $table->string('user_id');
            $table->boolean('state')->default(false);
            $table->timestamps();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
        });

每个用户都可以拥有多个games,因此我希望每个game->user_id都与用户的ID匹配。

我有以下功能,我创建了一个用户:

 public function createNewUser(){

        // Check here if user is about to win,

        $mUniqueID = uniqid("",true); // create an id
        $user = new User();
        $user->id = $mUniqueID;
        $saved = $user->save();


        $user = User::find($mUniqueID);
        $currentGame = new UserGame(['state' => false]); // It is in 'fillable' array - boolean
        $user->games()->save($currentGame);

        $mUserInformation = [
            'mUniqueID' => $mUniqueID,
            'game_id'   => $user->games()->latest()->first(),
        ];

        if($saved)
            return $mUserInformation;
        else
            return redirect()->route('game');
    }

我得到的错误:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败   (db_nameuser_games,CONSTRAINT user_games_user_id_foreign   FOREIGN KEY(user_id)REFERENCES usersid)ON DELETE CASCADE)   (SQL:插入user_gamesstateuser_idupdated_at,   created_at)值(0,59380,2017-06-07 14:18:52,2017-06-07   14点18分52秒))

我无法理解为什么会出现此错误。如果您需要更多信息,请询问,我会提供。

编辑1:

此外,在我的数据库中,用户的ID为:59380b495c1942.30562655,但错误仅提及59380,不应该是59380b495c1942.30562655吗?

编辑2:

  

User.php模型

    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
// all fillables here
        ];

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

        public function games()
        {

            return $this->hasMany('App\UserGame');
        }

    }
  

UserGame.php模型

class UserGame extends Model
{
    protected $fillable = [
        'state'
    ];


    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

1 个答案:

答案 0 :(得分:0)

因此,如果您想在/config/database.php中使用InnoDB引擎,请更改'engine'=> null,'engine'=> 'InnoDB的'

要使用uuid,您可以在config / app.php中添加别名后添加$table->increments('id')添加laravel-uuid

将迁移$table->uuid('id')更改为$table->primary('id')并添加$incrementing = false;

在模型中添加公开namespace App; use Webpatser\Uuid\Uuid; trait Uuids { protected static function boot() { parent::boot(); static::creating(function ($model) { $model->{$model->getKeyName()} = Uuid::generate()->string; }); } } 希望帮助你

最后添加特质

se Uuids

在模型中还添加u {{1}};