Run raw SQL in migration

前端 未结 2 1476
暗喜
暗喜 2020-12-14 00:42

I was trying with whatever syntax and can\'t think how can I write this correctly:

Schema::table(\'users\', function(Blueprint $table){
    $sql = <<&l         


        
相关标签:
2条回答
  • 2020-12-14 00:51

    The issue (as @postashin said) was the backticks.

    As of Laravel 5 (not sure about Laravel 4), you could have done this:

    DB::statement('ALTER TABLE `users` MODIFY `age` DATETIME');
    

    In fact you didn't even need the back ticks as they don't need escaping. So you could have just written:

    DB::statement('ALTER TABLE users MODIFY age DATETIME');
    

    You do not need this in the closure either if you are just executing a database statement.

    However a better approach to what you are doing is as follows:

    Schema::table('users', function(Blueprint $table) {
        $table->dateTime('age')->change();
    });
    

    Note the last solution can sometimes raise an error due to a bug in Doctrine, which usually occurs if you have an enum in the table (not just the column you are changing).

    For more information, see Laravel Database Migration - Modifying Column

    0 讨论(0)
  • 2020-12-14 00:54

    Use back-ticks instead of single quotes to escape identifiers in MySQL:

    alter table `users` modify `age` datetime
    

    In this particular case you can omit escaping at all:

    alter table users modify age datetime
    
    0 讨论(0)
提交回复
热议问题