解决laravel数据表迁移SQLSTATE[42000]问题

本文针对Laravel中因字段名过长引发的SQL错误,提供了解决方案,包括修改`roles`表结构,将`guard_name`字段长度缩短,并确保唯一性约束的合理设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 报错信息如下:
	 SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `roles` add unique `roles_name_guard_name_unique`(`name`, `guard_name`))

  at F:\php\laravel-admin-cms-master\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕

  1   F:\php\laravel-admin-cms-master\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes")

  2   F:\php\laravel-admin-cms-master\vendor\laravel\framework\src\Illuminate\Database\Connection.php:485
      PDOStatement::execute()
  • 最有效解决办法
    • 根据对应报错字段信息,直接设置该字段key长度即可,不需要添加Schema::defaultStringLength(191);如下图
     Schema::create($tableNames['roles'], function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('name');
           $table->string('title')->default ('');
           $table->string('guard_name',50);
           $table->timestamps();
    
           $table->unique(['name', 'guard_name']);
       });
       
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值