Programing

하나의 특정 Laravel 마이그레이션 실행 (단일 파일)

lottogame 2020. 12. 3. 07:22
반응형

하나의 특정 Laravel 마이그레이션 실행 (단일 파일)


laravel 4에서 All Outstanding Migrations를 실행하고 싶지 않습니다. 5 개의 마이그레이션이 있습니다. 이제 하나의 마이그레이션 만 실행하고 싶습니다. 대신 : php artisan migrate 나는 다음과 같은 특정 마이그레이션을 실행하고 싶습니다. php artisan migrate MY_MIGRATION_TO_RUN


잘못하고있는 것 같습니다.

마이그레이션은 Laravel 에서 생성 된 정확한 순서대로 하나씩 실행되도록 만들어 졌으므로 실행 및 실행 순서를 추적 할 수 있습니다. 이렇게하면 라 라벨은 데이터베이스를 손상시키지 않고 마이그레이션 일괄 처리를 안전하게 롤백 할 수 있습니다.

사용자에게 수동으로 실행할 수있는 권한을 부여하면 데이터베이스에서 변경 사항을 롤백하는 방법을 알 수 없게됩니다.

정말로 데이터베이스에서 무언가를 실행해야하는 경우 DDL 스크립트를 생성하고 웹 서버에서 수동으로 실행하는 것이 좋습니다.

또는 새 마이그레이션을 만들고 artisan을 사용하여 실행하십시오.

편집하다:

먼저 실행해야하는 경우 먼저 생성해야합니다.

순서를 변경해야하는 경우 파일 이름을 첫 번째로 변경하십시오. 마이그레이션은 timetemp로 생성됩니다.

2013_01_20_221554_table

이 이전에 새 마이그레이션을 만들려면 이름을 지정할 수 있습니다.

2013_01_19_221554_myFirstMigration

이미 실행 된 마이그레이션을 app / config / database / migrations / 폴더 밖으로 이동하십시오. 그런 다음 명령을 실행합니다 php artisan migrate. 나를위한 매력처럼 일했다.


마이그레이션을 더 많은 폴더에 넣고 다음과 같이 실행할 수 있습니다.

php artisan migrate --path=/app/database/migrations/my_migrations

Laravel 4 마이그레이션을 실행할 때 두려움을 덜어주는 멋진 스 니펫 php artisan migrate --pretend. 이것은 실제 마이그레이션을 실행 한 경우 실행되었을 SQL 만 출력합니다.

초기 4 개의 마이그레이션이 이미 실행 된 것 같습니다. 나는 당신 php artisan migrate이 새롭고 최근의 마이그레이션만을 실행할 것이라고 생각 합니다.

조언 : 모든 up () 및 down ()이 예상대로 작동하는지 확인하십시오. 마이그레이션을 실행할 때 up (), down (), up ()을 실행하여 테스트하는 것을 좋아합니다. down ()을 up () 100 % 퍼센트와 일치시키지 않았기 때문에 5-6 개의 마이그레이션을 가져오고 번거 로움없이 롤백 할 수 없다는 것을 깨닫는 것은 끔찍한 일입니다.

내 2 센트! (가) 희망 --pretend하는 데 도움이됩니다.


마이그레이션을 다시 실행하는 유일한 방법은 더러운 마이그레이션입니다. 데이터베이스를 열고 마이그레이션 테이블에서 마이그레이션을 나타내는 행을 삭제해야합니다.

그런 다음 php artisan migrate를 다시 실행하십시오.


다음과 같이 터미널에서 마이그레이션을위한 별도의 디렉토리를 만들 수 있습니다.

mkdir /database/migrations/my_migrations

그런 다음 실행할 특정 마이그레이션을 해당 디렉터리로 이동하고 다음 명령을 실행합니다.

php artisan migrate --path=/database/migrations/my_migrations

도움이 되었기를 바랍니다!


다른 게시물에서이 대답을했지만 이렇게 할 수 있습니다. 실행 artisan migrate하여 모든 마이그레이션을 실행 한 다음 다음 SQL 명령을 사용하여 마이그레이션 테이블을 업데이트하여 마이그레이션이 한 번에 하나씩 실행 된 것처럼 보이게합니다.

SET @a = 0;  
UPDATE migrations SET batch = @a:=@a+1;

그러면 배치 열이 1, 2, 3, 4 등으로 변경 됩니다. 특정 마이그레이션에만 영향을 미치려면 WHERE batch>=...여기에 조건을 추가하고 의 초기 값을 업데이트하십시오 @a.

그런 다음 artisan migrate:rollback필요한만큼 할 수 있으며 한 번에 하나씩 마이그레이션을 단계별로 진행합니다.


내가 아는 한 가지 쉬운 방법은 로컬 호스트 에서만 사용할 수 있습니다.

  1. 필요에 따라 마이그레이션 파일 수정
  2. phpMyAdmin 또는 데이터베이스 테이블을 보는 데 사용하는 모든 항목을 엽니 다.
  3. 원하는 테이블을 찾아서 놓습니다.
  4. 마이그레이션 테이블을 찾아서 엽니 다.
  5. 마이그레이션 필드 아래의이 테이블에서 원하는 테이블 이름을 찾아 해당 행을 삭제하십시오.
  6. 마지막으로 php artisan migrate명령 줄 또는 터미널에서 명령 실행합니다 . 이것은 데이터베이스의 마이그레이션 테이블에 존재하지 않는 테이블 만 마이그레이션합니다.

이 방법은 완전히 안전하며 비전문적 인 방법으로 보이지만 여전히 완벽하게 작동하는 동안 오류나 문제를 일으키지 않습니다.

행운을 빕니다


테스트 목적으로 만 사용하는 경우 다음과 같이합니다.

제 경우에는 여러 마이그레이션이 있으며 그중 하나에는 앱 설정이 포함되어 있습니다.

앱을 테스트하는 동안 모든 마이그레이션이 이미 설정되어있는 것은 아니지만 단순히 새 폴더 "미래"로 이동합니다. 이 폴더는 장인이 건드리지 않고 원하는 마이그레이션 만 실행합니다.

더러운 해결 방법이지만 작동합니다 ...


최신 마이그레이션 파일을 실행하려면 다음을 수행하십시오.

php artisan migrate

다음을 사용하여 마이그레이션을 추가하기 전으로 되돌릴 수도 있습니다.

php artisan migrate: rollback

나도 같은 문제가 있습니다. 다음과 같이 첫 번째 마이그레이션 파일에 테이블 생성 코드를 복사합니다.

  public function up()
    {
        Schema::create('posts', function(Blueprint $table){
            $table->increments('id');
            // Other columns...
            $table->timestamps();
        });
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            // Other columns...
            $table->softDeletes()->nullable();
        });
    }

또한 테이블의 batch열 번호를 변경 (감소) 할 수 있습니다 migrations;)

그런 다음 php artisan migrate.


적용하지 않으려는 경우 마이그레이션에서 예외를 throw하면 마이그레이션의 전체 프로세스가 중지됩니다.

이 접근 방식을 사용하면 여러 마이그레이션을 여러 단계로 나눌 수 있습니다.


너무 간단 ...! 마이그레이션 폴더로 이동하십시오. 모든 마이그레이션 파일을 다른 폴더로 이동합니다. 그런 다음 모든 마이그레이션을 마이그레이션 폴더로 하나씩 반환하고 그중 하나에 대한 마이그레이션을 실행하십시오 (php artisan). 마스터 마이그레이션 폴더에 잘못된 마이그레이션 파일을 삽입하고 명령 프롬프트에서 php artisan migrate를 실행하면 오류가 발생합니다.


라인 1에서 리턴을 사용했기 때문에 이전 db가 그대로 유지됩니다.

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        return;  // This Line
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 50);
            $table->string('slug', 50)->unique();
            $table->integer('role_id')->default(1);
            $table->string('email', 50)->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('mobile', 10)->unique();
            $table->timestamp('mobile_verified_at')->nullable();
            $table->text('password');
            $table->integer('can_login')->default(1);
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        return;// This Line
        Schema::dropIfExists('users');
    }
}

이것은 제가 사용하는 잘못된 접근 방식입니다 .. 마이그레이션하려는 특정 파일을 제외한 다른 마이그레이션 파일을 삭제하고 마이그레이션이 완료된 후 PHP artisan migrate를 실행합니다. 휴지통으로 이동하여 삭제 된 파일을 복원합니다.


여전히 이것에 관심이있는 분들을 위해 라 라벨 5 업데이트 : 라 라벨은 한 번에 하나의 마이그레이션 파일을 실행하는 옵션을 구현했습니다 (버전 5.7에서).

이제 이것을 실행할 수 있습니다 : php artisan migrate --path=/database/migrations/my_migration.php ( 여기에 답변 )

Illuminate\Database\Migrations\Migrator::getMigrationFiles()이제이 코드가 포함되어 있기 때문에 : return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');( 소스 코드 참조 . )


그러나 제 사용 사례에서는 실제로 하나 또는 전체가 아닌 일련의 마이그레이션을 동시에 실행하고 싶었습니다 .

그래서 저는 Laravel 방식으로 이동하여 사용할 파일을 결정하는 Migrator의 다른 구현을 등록했습니다.

/**
 * A migrator that can run multiple specifically chosen migrations.
 */
class MigrationsSetEnabledMigrator extends Migrator
{
    /**
     * @param Migrator $migrator
     */
    public function __construct(Migrator $migrator)
    {
        parent::__construct($migrator->repository, $migrator->resolver, $migrator->files);

        // Compatibility with versions >= 5.8
        if (isset($migrator->events)) {
            $this->events = $migrator->events;
        }
    }

    /**
     * Get all of the migration files in a given path.
     *
     * @param  string|array $paths
     * @return array
     */
    public function getMigrationFiles($paths)
    {
        return Collection::make($paths)->flatMap(function ($path) {
            return Str::endsWith($path, ']') ? $this->parseArrayOfPaths($path) :
                (Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path . '/*_*.php'));
        })->filter()->sortBy(function ($file) {
            return $this->getMigrationName($file);
        })->values()->keyBy(function ($file) {
            return $this->getMigrationName($file);
        })->all();
    }

    public function parseArrayOfPaths($path)
    {
        $prefix = explode('[', $path)[0];
        $filePaths = explode('[', $path)[1];
        $filePaths = rtrim($filePaths, ']');

        return Collection::make(explode(',', $filePaths))->map(function ($filePath) use ($prefix) {
            return $prefix . $filePath;
        })->all();
    }
}

Migrate 명령이 IoC에 등록 될 때이를 액세스하는 방식이기 때문에 'migrator'(로 액세스 할 수 있도록 $app['migrator']) 컨테이너 에 등록해야합니다. 이를 위해이 코드를 서비스 제공 업체에 넣습니다 (제 경우에는 DatabaseServiceProvider).

    public function register()
    {
        $this->app->extend('migrator', function ($migrator, $app) {
            return new MultipleSpecificMigrationsEnabledMigrator($migrator);
        });

        // We reset the command.migrate bind, which uses the migrator - to 
        // force refresh of the migrator instance.
        $this->app->instance('command.migrate', null);
    }

그런 다음 이것을 실행할 수 있습니다.

php artisan migrate --path=[database/migrations/my_migration.php,database/migrations/another_migration.php]

쉼표로 구분 된 여러 마이그레이션 파일을 확인하십시오.

It is tested and working in Laravel 5.4 and should be Laravel 5.8 compatible.

Why?

For anyone interested: the usecase is updating the version of database along with it's data.

Imagine, for example, that you wanted to merge the street and house number of all users into new column, let's call it street_and_house. And imagine you wanted to do that on multiple installations in a safe and tested way - you would probably create a script for that (in my case, I create data versioning commands - artisan commands).

To do such an operation, you first have to load the users into memory; then run the migrations to remove the old columns and add the new one; and then for each user assign the street_and_house=$street . " " . $house_no and save the users. (I am simplifying here, but you can surely imagine other scenarios)

And I do not want to rely on the fact that I can run all the migrations at any given time. Imagine that you wanted to update it from let's say 1.0.0 to 1.2.0 and there were multiple batches of such updates – performing any more migrations could break your data, because those migrations must be handled by their own dedicated update command. Therefore, I want to only run the selected known migrations which this update knows how to work with, then perform operations on the data, and then possibly run the next update data command. (I want to be as defensive as possible).

To achieve this, I need the aforementioned mechanism and define a fixed set of migrations to be run for such a command to work.

Note: I would have preferred to use a simple decorator utilizing the magic __call method and avoid inheritance (a similar mechanism that Laravel uses in the \Illuminate\Database\Eloquent\Builder to wrap the \Illuminate\Database\Query\Builder), but the MigrateCommand, sadly, requires an instance of Migrator in it's constructor.


Final note: I wanted to post this answer to the question How can I run specific migration in laravel , as it is Laravel 5 - specific. But I can not - since that question is marked as a duplicate of this one (although this one is tagged as Laravel 4).


You can use below solution:

  1. create your migration.
  2. check your migration status like: php artisan migrate:status.
  3. copy the full name of new migration and do this like: php artisan migrate:rollback --path:2018_07_13_070910_table_tests.
  4. and then do this php artisan migrate.

finally, you migrate specific table. Goodluck.


You may type the following command:

php artisan migrate --help

...

--path[=PATH] The path(s) to the migrations files to be executed (multiple values allowed)

...

If it does show an option called "--path" (like the upper example) that means your Laravel version supports this parameter. If so, you're in luck can then you can type something like:

php artisan migrate --path=/database/migrations/v1.0.0/

Where "v.1.0.0" is a directory that exists under your "/database/migrations" directory that holds those migrations you want to run for a certain version.

If not, then you can check in your migrations table to see which migrations have already been run, like this:

SELECT * FROM migrations;

And then move out of your "/database/migrations" folder those which were executed. By creating another folder "/databases/executed-migrations" and moving your executed migrations there.

After this you should be able to execute:

php artisan migrate

Without any danger to override any existing table in your schema/database.

참고URL : https://stackoverflow.com/questions/19102197/running-one-specific-laravel-migration-single-file

반응형