Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

php - Run raw SQL in migration

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

Schema::table('users', function(Blueprint $table){
    $sql = <<<SQL
        ALTER TABLE 'users' MODIFY 'age' DATETIME
    SQL;
    DB::connection()->getPdo()->exec($sql);
});

also tried with

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

and double quotation marks and so on. I always get the following when I run the migration:

Syntax error or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MariaDB server version for the right syntax to use near ''users' MODIFY 'age' DATETIME' at line 1

Yes, I have checked, MariaDB uses MySQL's syntax (at least for this case).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...