IT

라 라벨 마이그레이션 오류 : 구문 오류 또는 액세스 위반 : 1071 지정된 키가 너무 깁니다.

lottoking 2020. 7. 3. 18:04
반응형

라 라벨 마이그레이션 오류 : 구문 오류 또는 액세스 위반 : 1071 지정된 키가 너무 깁니다. 최대 키 길이는 767 바이트입니다.


Laravel 5.4에서 마이그레이션 오류 php artisan make:auth

[Illuminate \ Database \ QueryException] SQLSTATE [42000] : 구문 오류 또는 액세스 위반 : 1071 지정된 키가 너무 깁니다. 최대 키 길이는 767 바이트입니다 (SQL : alter tabl e usersadd unique users_email_unique( email))

[PDOException] SQLSTATE [42000] : 구문 오류 또는 액세스 위반 : 1071 지정된 키가 너무 깁니다. 최대 키 길이는 767 바이트입니다.


공식 문서 에 따르면 이것을 쉽게 해결할 수 있습니다.

AppServiceProvider.php에 다음 코드 추가 (/app/Providers/AppServiceProvider.php)

use Illuminate\Support\Facades\Schema; //NEW: Import Schema

function boot()
{
    Schema::defaultStringLength(191); //NEW: Increase StringLength
}

MySQL은 항상 4 바이트 인 UTF8 필드의 최대량을 예약하므로 DEFAULT CHARACTER SET로 255 + 255를 사용합니다. utf8mb4 COLLATE utf8mb4_unicode_ci; 767 최대 키 길이 제한을 초과했습니다. @scaisedge 작성


위의 솔루션과 공식 솔루션이 추가되는 이유를 모르겠습니다.

Schema::defaultStringLength(191);

에서 AppServiceProvider나를 위해 작동하지 않았다. 효과가 있었던 database.php것은 config폴더 에서 파일을 편집하는 것이 었습니다 . 그냥 편집

'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',

'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',

작동해야합니다. 도움이 되길 바랍니다.


나는이 답변을 여기에 추가하고 quickest있습니다. 기본 데이터베이스 엔진을 'InnoDB'켜기로 설정하십시오 .

/config/database.php

'mysql' => [
    ...,
    ...,
    'engine' => 'InnoDB',
 ]

그런 다음 실행 php artisan config:cache하여 구성 캐시를 지우고 새로 고칩니다.


에서 AppServiceProvider.php, 당신은 파일의 코드 상단을 포함한다.

use Illuminate\Support\Facades\Schema;

public function boot()
{
Schema::defaultStringLength(191);
}

이 문제는 데이터베이스 버전에 따라 Laravel 5.4에서 발생합니다.

문서 에 따르면 ( Index Lengths & MySQL / MariaDB섹션에서)

라 라벨은 utf8mb4기본적으로 문자 세트를 사용하는데 , 여기에는 데이터베이스에 "이모 지"를 저장하는 기능이 포함됩니다. 5.7.7 릴리스 이전의 MySQL 버전 또는 10.2.2 릴리스 이전의 MariaDB를 실행중인 경우, MySQL이 인덱스를 작성하기 위해 마이그레이션에서 생성 된 기본 문자열 길이를 수동으로 구성해야 할 수도 있습니다. 에서 Schema::defaultStringLength메소드 를 호출하여이를 구성 할 수 있습니다 AppServiceProvider.

다시 말해 <ROOT>/app/Providers/AppServiceProvider.php:

// Import Schema
use Illuminate\Support\Facades\Schema;
// ...

class AppServiceProvider extends ServiceProvider
{

public function boot()
{
    // Add the following line
    Schema::defaultStringLength(191);
}

// ...

}

그러나 다른 답변에 대한 의견에서는 다음과 같이 말합니다.

이 솔루션에주의하십시오. 예를 들어 전자 메일 필드를 색인화하면 저장된 전자 메일의 최대 길이는 191 자입니다. 이것은 공식 RFC 상태보다 적습니다.

따라서 설명서에는 다른 솔루션도 제안되어 있습니다.

또는 innodb_large_prefix데이터베이스에 대한 옵션을 활성화 할 수 있습니다. 이 옵션을 올바르게 활성화하는 방법에 대한 지침은 데이터베이스 설명서를 참조하십시오.


변경하고 싶지 않은 사람에게 AppServiceProvider.php. (제 의견으로 AppServiceProvider.php는 마이그레이션을 위해서만 변경하는 것이 좋지 않습니다 )

database/migrations/아래와 같이 데이터 길이를 마이그레이션 파일에 다시 추가 할 수 있습니다 .

create_users_table.php

$table->string('name',64);
$table->string('email',128)->unique();

create_password_resets_table.php

$table->string('email',128)->index();

명령을 사용하는 동안 laravel에서 작업하는 동안이 오류가 발생 php artisan migrate하면 파일에 두 줄을 추가하십시오 : app-> Providers-> AppServiceProvider.php

  1. use Schema;
  2. Schema::defaultStringLength(191);

이 이미지 를 확인 하십시오 . 그런 다음 php artisan migrate명령을 다시 실행 하십시오.


app / Providers / AppServiceProvider.php에이 줄을 업데이트하고 삽입하십시오

use Illuminate\Support\Facades\Schema;  // add this line at top of file

public function boot()
{
    Schema::defaultStringLength(191); // add this line in boot method
}

나는 나를 위해 두 가지 해결책추가 하고 있습니다.

1 차 sollution입니다 :

  1. 열기 database.php의 파일 insde 설정 디렉토리 / 폴더에 있습니다.
  2. 편집 'engine' => null,하다'engine' => 'InnoDB',

    이것은 나를 위해 일했습니다.

두 번째 용해는 :

  1. 열기 database.php의 파일 insde 설정 디렉토리 / 폴더에 있습니다.
    2. 편집
    'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci',

    'charset' => 'utf8', 'collation' => 'utf8_unicode_ci',


행운을 빕니다


이 문제를 해결하고 내 데이터베이스 ( 'charset'=> 'utf8')( 'collation'=> 'utf8_general_ci') 과 같이 config-> database.php 파일을 편집 했으므로 내 문제는 다음과 같이 코드를 해결합니다. 따르다:

'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

1-/config/database.php 이 줄로 이동

'mysql' => [
    ...,
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    ...,
    'engine' => null,
 ]

그것들을 다음과 같이 변경하십시오 :

'mysql' => [
    ...,
    'charset' => 'utf8',
    'collation' => 'utf8_unicode_ci',
    ...,
    'engine' => 'InnoDB',
 ]

2-라php artisan config:cache 라벨을 재구성하기 위해 실행

3- 데이터베이스에서 기존 테이블을 삭제 한 후 php artisan migrate다시 실행


이 오류에 대한 두 가지 해결책을 찾았습니다.

옵션 1:

열려있는 사용자password_reset 테이블을 데이터베이스 / 마이그레이션의 폴더

그리고 이메일 길이를 변경하십시오.

$table->string('email',191)->unique();

옵션 2 :

app/Providers/AppServiceProvider.php파일을 열고 boot()메소드 내부에서 기본 문자열 길이를 설정하십시오.

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

길이 제한을 설정하는 대신 다음과 같이 제안했습니다.

내부

config / database.php

이 줄을 mysql로 ​​바꾸십시오.

'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',

...에

'engine' => null,

에서 AppServiceProvider.php의 파일 :

 use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

이미 지정한 바와 같이 App / Providers의 AppServiceProvider.php에 추가합니다

use Illuminate\Support\Facades\Schema;  // add this

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191); // also this line
}

you can see more details in the link bellow (search for "Index Lengths & MySQL / MariaDB") https://laravel.com/docs/5.5/migrations

BUT WELL THAT's not what I published all about! the thing is even when doing the above you will likely to get another error (that's when you run php artisan migrate command and because of the problem of the length, the operation will likely stuck in the middle. solution is below, and the user table is likely created without the rest or not totally correctly) we need to roll back. the default roll back will not work. because the operation of migration didn't like finish. you need to delete the new created tables in the database manually.

we can do it using tinker as in below:

L:\todos> php artisan tinker

Psy Shell v0.8.15 (PHP 7.1.10 — cli) by Justin Hileman

>>> Schema::drop('users')

=> null

I myself had a problem with users table.

after that you're good to go

php artisan migrate:rollback

php artisan migrate


If you want to change in AppServiceProvider then you need to define the length of email field in migration. just replace the first line of code to the second line.

create_users_table

$table->string('email')->unique();
$table->string('email', 50)->unique();

create_password_resets_table

$table->string('email')->index();
$table->string('email', 50)->index();

After successfully changes you can run the migration.
Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migration table.


As outlined in the Migrations guide to fix this, all you have to do is edit your app/Providers/AppServiceProvider.php file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migrations table.

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

After that everything should work as normal.


Schema::defaultStringLength(191); will define the length of all strings 191 by default which may ruin your database. You must not go this way.

Just define the length of any specific column in the database migration class. For example, I'm defining the "name", "username" and "email" in the CreateUsersTable class as below:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 191);
            $table->string('username', 30)->unique();
            $table->string('email', 191)->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

This is common since Laravel 5.4 changed the default database charater set to utf8mb4. What you have to do, is: edit your App\Providers.php by putting this code before the class declaration

use Illuminate\Support\Facades\Schema;

Also, add this to the 'boot' function Schema::defaultStringLength(191);


If you don't have any data assigned already to you database do the following:

  1. Go to app/Providers/AppServiceProvide.php and add

use Illuminate\Support\ServiceProvider;

and inside of the method boot();

Schema::defaultStringLength(191);

  1. Now delete the records in your database, user table for ex.

  2. run the following

php artisan config:cache

php artisan migrate


As outlined in the Migrations guide to fix this all you have to do is edit your AppServiceProvider.php file and inside the boot method set a default string length:

//edit your AppServiceProvider.php file contains in providers folder
use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Hope this will help you..cheers..


I have just modified following line in users and password_resets migration file.

Old : $table->string('email')->unique();

New : $table->string('email', 128)->unique();


In order to avoid changing anything in your code, simply update your MySQL server to at least 5.7.7

Reference this for more info : https://laravel-news.com/laravel-5-4-key-too-long-error


I think to force StringLenght to 191 is a really bad idea. So I investigate to understand what is going on.

I noticed that this message error :

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

Started to show up after I updated my MySQL version. So I've checked the tables with PHPMyAdmin and I've noticed that all the new tables created were with the collation utf8mb4_unicode_ci instead of utf8_unicode_ci for the old ones.

In my doctrine config file, I noticed that charset was set to utf8mb4, but all my previous tables were created in utf8, so I guess this is some update magic that it start to work on utf8mb4.

Now the easy fix is to change the line charset in your ORM config file. Then to drop the tables using utf8mb4_unicode_ci if you are in dev mode or fixe the charset if you can't drop them.

For Symfony 4

change charset: utf8mb4 to charset: utf8 in config/packages/doctrine.yaml

Now my doctrine migrations are working again just fine.


The recommended solution is to enable innodb_large_prefix option of MySQL so you won't be getting into subsequent problems. And here is how to do that:

Open the my.ini MySQL configuration file and add the below lines under the [mysqld] line like this.

[mysqld]
innodb_file_format = Barracuda
innodb_large_prefix = 1
innodb_file_per_table = ON

After that, save your changes and restart your MySQL service.

Rollback if you need to and then re-run your migration.


Just in case your problem still persists, go to your database configuration file and set

'engine' => null, to 'engine' => 'innodb row_format=dynamic'

Hope it helps!


For anyone else who might run into this, my issue was that I was making a column of type string and trying to make it ->unsigned() when I meant for it to be an integer.


The approached that work here was pass a second param with the key name (a short one):

$table->string('my_field_name')->unique(null,'key_name');

I was getting this error even though I already had (actually because I already had) Schema::defaultStringLength(191); in my AppServiceProvider.php file.

The reason is because I was trying to set a string value in one of my migrations to a value higher than 191:

Schema::create('order_items', function (Blueprint $table) {
    $table->primary(['order_id', 'product_id', 'attributes']);
    $table->unsignedBigInteger('order_id');
    $table->unsignedBigInteger('product_id');
    $table->string('attributes', 1000); // This line right here
    $table->timestamps();
});

Removing the 1000 or setting it to 191 solved my issue.


Changing my local database server type from "mariadb" to "mysql" fixed this for me without having to edit any Laravel files.

I followed this tutorial to change my db server type: https://odan.github.io/2017/08/13/xampp-replacing-mariadb-with-mysql.html


You can set a string length of the indexed field as follows:

  $table->string('email', 200)->unique();

참고URL : https://stackoverflow.com/questions/42244541/laravel-migration-error-syntax-error-or-access-violation-1071-specified-key-wa

반응형