php 在迁移中运行原始 SQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28787293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run raw SQL in migration
提问by Milkncookiez
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
语法错误或访问冲突:1064 您的 SQL 语法有错误;检查
与您的 MariaDB 服务器版本相对应的手册,了解在第 1 行的“用户”修改“年龄”日期时间附近使用的正确语法
Yes, I have checked, MariaDB uses MySQL's syntax (at least for this case).
是的,我已经检查过,MariaDB 使用 MySQL 的语法(至少在这种情况下)。
回答by potashin
Use back-ticks instead of single quotes to escape identifiers in MySQL:
在 MySQL 中使用反引号代替单引号来转义标识符:
alter table `users` modify `age` datetime
In this particular case you can omit escaping at all:
在这种特殊情况下,您可以完全省略转义:
alter table users modify age datetime
回答by Yahya Uddin
The issue (as @postashin said) was the backticks.
问题(正如@postashin 所说)是反引号。
As of Laravel 5 (not sure about Laravel 4), you could have done this:
从 Laravel 5(不确定 Laravel 4)开始,你可以这样做:
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).
请注意,最后一个解决方案有时会由于 Doctrine 中的错误而引发错误,如果表中有枚举(而不仅仅是要更改的列),则通常会发生这种错误。
For more information, see Laravel Database Migration - Modifying Column
有关更多信息,请参阅Laravel 数据库迁移 - 修改列