code

Laravel 마이그레이션 테이블이 이미 존재하지만 이전 항목이 아닌 새 항목을 추가하고 싶습니다.

codestyles 2021. 1. 9. 09:55
반응형

Laravel 마이그레이션 테이블이 이미 존재하지만 이전 항목이 아닌 새 항목을 추가하고 싶습니다.


이전에 사용자 테이블을 만들었습니다. 이제 스키마 내에 새 books 테이블을 만들기 위해 새 마이그레이션을 만들었습니다. 명령을 실행하려고 할 때

php artisan migrate

이것은 보여준다:

[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' alre
ady exists (SQL: create table `users` (`id` int unsigned not null auto_incr
ement primary key, `username` varchar(255) not null, `email` varchar(255) n
ot null, `password` varchar(255) not null, `created_at` timestamp default 0
 not null, `updated_at` timestamp default 0 not null) default character set
 utf8 collate utf8_unicode_ci)

다음은 새 마이그레이션 테이블입니다.

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateBooksTable extends Migration {
    public function up()
    {
        Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('books');
    }
}

오류를 어떻게 제거 할 수 있습니까?


당신은 실행해야

php artisan migrate:rollback

그것도 실패하면 마이그레이션 테이블이 엉망이 된 것처럼 보이거나 이전 롤백을 실행할 때 사용자 테이블이 테이블을 삭제하지 않았기 때문에해야 할 모든 테이블을 삭제하십시오.

편집하다:

이것이 발생하는 이유는 이전에 롤백을 실행했으며 코드에 오류가 있거나 테이블을 삭제하지 않았기 때문입니다. 그러나 이것은 여전히 ​​laravel 마이그레이션 테이블을 엉망으로 만들고 우려되는 한 사용자 테이블을 밀어 올린 기록이 없습니다. 그러나 사용자 테이블이 이미 존재하며이 오류가 발생합니다.


v5.x에서는 여전히 문제에 직면 할 수 있습니다. 따라서 먼저 관련 테이블을 수동으로 삭제하십시오.

php artisan tinker

그때

Schema::drop('books')

(그리고로 종료 q)

지금, 당신은 성공적으로 할 수 php artisan migrate:rollbackphp artisan migrate.

이 문제가 반복적으로 발생하면 down()마이그레이션 메서드가 올바른 테이블 이름을 표시 하는지 확인해야합니다 . (테이블 이름을 변경 한 경우 문제가 될 수 있습니다.)


나도 같은 문제가 있었다. 그 이유는 migrations 폴더 파일 이름데이터베이스 의 마이그레이션 이름 과 일치하지 않기 때문입니다 (migrations 표 참조). 동일해야합니다.


또한 Schema::create('books', function(Blueprint $table)다음 코드에 대해 삽입 할 수 있습니다.Schema::drop('books');


를 사용 php artisan migrate:fresh하여 모든 테이블을 삭제 한 다음 마이그레이션 할 수 있습니다 . 도움이되기를 바랍니다.


편집 : (laravel의 경우)

laravel에서 프로젝트를 작업하는 동안이 문제를 발견했습니다. 내 테이블이 엉망이되어 열을 자주 변경해야했습니다. 일단 테이블이 있으면 php artisan migrate더 이상 뛸 수 없었습니다 .

나는 문제를 제거하기 위해 다음을 수행했습니다.

  1. 데이터베이스에서 테이블 삭제 [마이그레이션 테이블을 포함한 모든 테이블]
  2. $ composer dump-autoload -o
  3. php artisan migrate

루멘에 관한 이전 코멘트

[글쎄, 파티에 꽤 늦었 어 (그리고 내가 찾던 파티와는 다른 파티일지도 모른다). 나는 머리를 부딪 치고 큰 소리로 비명을 질렀고 회색 해골의 은혜로 해결책을 찾았다.]

루멘을 사용하여 편안한 앱을 개발 중이며 처음 사용합니다. 이것은 laraval과 lumen을 사용한 첫 번째 프로젝트 / 실험입니다. 내 의존성-

"require": {
    "php": ">=5.6.4",
    "laravel/lumen-framework": "5.4.*",
    "vlucas/phpdotenv": "~2.2",
    "barryvdh/laravel-cors": "^0.8.6",
    "league/fractal": "^0.13.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "phpunit/phpunit": "~5.0",
    "mockery/mockery": "~0.9.4"
}

어쨌든 어제 밤까지 모든 것이 괜찮 았지만 갑자기 phpunit이미 존재하는 테이블에 대해 불평하기 시작했습니다.

Caused by
PDOException: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'items' already exists

야! Items테이블이 데이터베이스에 있어야합니다. 그렇지 않으면 항목을 어떻게 저장해야합니까?

어쨌든 문제는 테스트 클래스에서만 지속되었지만 이상하게도 브라우저에는 없었습니다 (Chrome, firefox 및 postman 변경 헤더로 확인했습니다). 예상대로 데이터가 포함 된 JSON 응답을 받았습니다.

나는 데이터베이스를 떨어 많은 그것을 다시 migrate, refresh, rollback. 모든 것이 괜찮 았지만 phpunit.

필사적으로 마이그레이션 파일을 제거하고 (물론 백업을 먼저 수행했습니다) phpunit터미널 을 쳤 습니다. 다시 한 번 똑같습니다.

갑자기 나는 phpunit.xml테스트 목적으로 만 파일에 다른 데이터베이스 이름을 넣었다는 것을 기억했습니다 . 나는 그 데이터베이스를 확인하고 무엇을 추측한다! 라는 테이블이 items있습니다. 이 테이블을 수동으로 제거하고 실행 phpunit하면 모든 것이 제대로 작동하기 시작했습니다.

나는 미래의 참조를 위해서만 내 경험을 문서화하고 있으며 이것이 미래에 누군가에게 도움이 될 수 있기를 바랍니다.


나는 마이그레이션을 사용하지 않는 사람으로부터 진짜 나쁜 코드를 물려 받았다!?, 그래서 수동으로 파일 이름을 마이그레이션에 붙여넣고 후행 .php를 제거하는 것을 잊었다.

따라서 파일 이름과 마이그레이션 일치에도 불구하고 '테이블 존재'오류가 발생했습니다.

2018_05_07_142737_create_users_table.php-WRONG 2018_05_07_142737_create_users_table-정확함


모든 테이블을 삭제할 수 있지만 좋은 방법이 아닙니다. 대신이 명령을 시도하십시오.

php artisan migrate:fresh

명명 규칙을 올바르게 사용해야합니다. 나는 이것을 버전 laravel 5.7에서 테스트했습니다. 사이트가 서버에있을 때이 명령을 시도하지 않는 것이 중요합니다. 모든 정보를 삭제하기 때문입니다.


외래 키 제약을 엉망으로 만든 후 비슷한 문제가 발생했습니다. 내 테이블 중 하나 (노트)가 사라지고 하나는 MySQL에서 삭제 한 후에도 계속 돌아와서 (작업), 실행되지 못하게했습니다 : php artisan migrate/refresh/reset, 위의 42s01 예외가 발생했습니다.

내가 그것을 해결하기 위해 한 것은 ssh를 vagrant로 vagrant ssh, mysql -u homestead -p secret시작한 다음 MySQL ( ) 로 이동 한 다음 : DROP DATABASE homestead; Then CREATE DATABASE homestead; Then exit mysql and run:php artisan migrate`.

분명히이 솔루션은 방랑자 / 주택을 사용하지 않는 사람들에게는 효과가 없습니다. 어떤 식 으로든 이것이 적절한 워크 플로라고 주장하지 않지만 위의 것과 매우 유사한 내 문제를 해결했습니다.


내 대답이 더 도움이 될 것이라고 생각합니다. 나는 또한이 오류에 직면했다. 그런 다음 특정 마이그레이션 파일을 삭제하고 php artisan으로 다시 만들려고했습니다.

하지만 1 ~ 2 일 전에 마이그레이션에 대한 라라 캐스트 비디오를 보는 동안이 시점을 얻기 전에 롤백을 생각하고 특정 테이블을 마이그레이션했습니다. 어떤 이유로 특정 마이그레이션 파일을 삭제하고 다시 만들려고 시도했지만 그렇게하면 다음과 같은 결과가 나타납니다.

[ErrorException] include (C : \ wamp64 \ www \ laraveldeneme \ vendor \ composer /../../ database / migrations / 2017_01_09_082715_create_articles_table.php) : 스트림을 열지 못했습니다 : 해당 파일 또는 디렉토리가 없습니다.

해당 파일을 확인할 때 autoload_classmap.php 파일의 배열 맨 위에 아래 줄이 표시되었습니다.

'CreateArticlesTable'=> $ baseDir. '/ database / migrations / 2017_01_09_083946_create_articles_table.php',

마이그레이션 파일을 롤백하거나 삭제하더라도 마이그레이션 파일과 관련된 레코드는 composer autoload_classmap.php 파일에 남아 있습니다.

이 문제를 해결하기 위해 아래에서 내가 기억할 수없는 곳에서 composer 명령을 찾았습니다.

composer dump-autoload

이 코드를 작성하면 삭제 한 마이그레이션 파일과 관련된 줄이 사라집니다. 그런 다음 실행했습니다.

php artisan make:migration create_articles_table --create=articles

마지막으로 동일한 이름으로 마이그레이션 파일을 다시 만들었습니다.


데이터베이스에 모든 표를 놓은 다음

이 작업을 수행

php artisan migrate:refresh

마이그레이션 파일 편집

php artisan migrate:rollback

php artisan migrate 또 ^ _ ^

테이블을 완료했습니다!


롤백 후 테이블을 확인하고 삭제하십시오.

문제가 있으면 phpmyadmin과 같은 데이터베이스 응용 프로그램에서 수동으로 테이블을 삭제하십시오 (Mac 용 sequel pro를 사용하고 있습니다).

마이그레이션에서 다운 방법을 수정하십시오.

참고 : 롤백 한 다음 마이그레이션합니다 .. migrate : refresh를 사용하여 오류가 발생한 위치를 확인하지 마십시오.

그 후 테스트를 위해 새 db로 테스트 할 수 있습니다. 문제가 어디에 있는지 감지합니다.

질문도 읽어보세요


phpmyadmin으로 이동하여 laravel 용으로 만든 데이터베이스를 삭제 한 다음 다시 만든 다음 cmd (Windows를 사용하는 경우) 루트 프로젝트로 이동하여 php artisan migrate를 입력합니다.


테이블을 만들기 전에 항상 테이블 존재 여부를 확인할 수 있습니다.

    if(!Schema::hasTable('books')){
 Schema::create('books', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name');
            $table->string('auther');
            $table->string('area');
            $table->timestamps();
        });
}

php artisan migrate:rollback 

솔루션 확인 : 라 라벨 공식 솔루션

이 문제를 해결하기 위해 마이그레이션 가이드설명 된대로 app \ Providers \ AppServiceProvider.php 파일을 편집하고 부팅 메서드 내에서 기본 문자열 길이를 설정하면됩니다.

use Illuminate\Support\Facades\Schema;

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

위의 명령 후에 나머지 모든 테이블을 수동으로 삭제 한 다음 명령을 실행해야합니다.

php artisan migrate:fresh

먼저 데이터베이스에서 사용자 테이블을 삭제 한 다음 propmt 명령으로 이동하여

php artisan migrate

이 답변이 도움이된다고 생각합니다.


이것을 AppServiceProvider.php에 추가하십시오.

use Illuminate\Support\Facades\Schema;
public function boot() {
    Schema::defaultStringLength(191);
}

  1. 모든 테이블 데이터베이스 삭제
  2. database / migrations / 폴더의 두 파일 업데이트 : 2014_10_12_000000_create_users_table.php, 2014_10_12_100000_create_password_resets_table.php

2014_10_12_100000_create_password_resets_table.php

Schema::create('password_resets', function (Blueprint $table) {
     $table->string('email');
     $table->string('token');
     $table->timestamp('created_at')->nullable();
});

2014_10_12_000000_create_users_table.php

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

sequel-pro (내 사용자 테이블에 데이터가 없음)에서 "사용자"테이블을 삭제하여 문제를 해결 한 다음 실행할 수 있습니다. php artisan migrate

다음은 전후 스크린 샷입니다.

사용자 테이블 사용자를 삭제하기 전에

여기에 이미지 설명 입력

테이블 사용자를 삭제 한 후 여기에 이미지 설명 입력


  1. phpmyadmin 에서 모든 테이블을 수동으로 삭제하십시오 .

  2. 에서 각 마이그레이션 파일로 이동 합니다 database/migrations. 다음 두 코드를 찾아 제거하십시오.

    a)-> index () (2014_10_12_100000_create_password_resets_table.php 17 행)

    b) ->unique() (found at 2014_10_12_000000_create_users_table.php at line 19)

  3. Run php artisan migrate

  4. Done.

I think this happens because the latest laravel class (at 12th February 2018) has removed the function of ->index() and ->unique()


In laravel 5.4, If you are having this issue. Check this link

-or-

Go to this page in app/Providers/AppServiceProvider.php and add code down below

use Illuminate\Support\Facades\Schema;

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

Edit AppServiceProvider.php will be found at app/Providers/AppServiceProvider.php and add

use Illuminate\Support\Facades\Schema;

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

Then run

composer update

On your terminal. It helped me, may be it will work for you as well.


Drop all database table and run this line in your project path via CMD

php artisan migrate

I also had this issue, just came across this answer on a Youtube Video. Not sure if it's ideal, but it's the best I've seen.

Seems the AppServiceProvider.php file of the providers directory by giving the Schema a length. In this case 191. Works like magic.Screenshot. He then ran: php artisan migrate:fresh. Hope this works.


I had the same issue, the problem is in the name saved in the table migrations inside database, because in my database exists 2017_10_18_200000_name and in files 2016_10_18_200000_name, after change the name of file that work.


First check the migrations table in your DB and sure that your migration files in database folder in your project is equal to this table data. Sometimes if you create migration files by manual appear this error when run migrate command in composer.


DANGER - most of these answers will wipe your database and is not recommended for production use.

It's clear there are a lot of "solutions" for this problem, but all these solutions I read through are very destructive solutions and none of them work for a production database. Based on the number of solutions, it also seems that there could be several causes to this error.

My error was being caused by a missing entry in my migrations table. I'm not sure exactly how it happened but by adding it back in I no longer received the error.


Solution :Laravel Migration table already exists... || It Works in Laravel 5.8 also

app\Providers\AppServiceProvider.php file

and inside the boot method set a default string length:

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

and open

config\database.php

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

and change it to

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

save all the files and go to command prompt

php artisan migrate

Answer is very straight forward :

First take a backup of folder bootstrap/cache.

그런 다음 bootstrap / cache 폴더에서 모든 파일을 삭제합니다.

이제 실행 :

php artisan migrate 

데이터베이스를 만드는 데는 말 그대로 몇 초가 걸립니다.

민감한 데이터가있는 경우 현재 데이터베이스를 내 보냅니다.

마이그레이션을 확인하고 잘못된 방법을 모두 제거하십시오.

데이터베이스를 삭제하고 데이터베이스다시 만듭니다.

php artisan migrate

그런 다음 이전에 데이터베이스에 있던 데이터를 반환 할 수 있습니다.

참조 URL : https://stackoverflow.com/questions/26077458/laravel-migration-table-already-exists-but-i-want-to-add-new-not-the-older

반응형