Php 在laravel迁移中使用连字符(-)重命名列名
我试图运行laravel迁移,重命名数据库中的特定列,但我反复收到错误消息Php 在laravel迁移中使用连字符(-)重命名列名,php,laravel,database-migration,Php,Laravel,Database Migration,我试图运行laravel迁移,重命名数据库中的特定列,但我反复收到错误消息 class ModifyColumnName extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) {
class ModifyColumnName extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn("content-description", "content_description");
});
}
}
Illuminate\Database\QueryException: SQLSTATE[42000]: 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 '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)
我一直收到这个错误消息
class ModifyColumnName extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn("content-description", "content_description");
});
}
}
Illuminate\Database\QueryException: SQLSTATE[42000]: 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 '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)
用连字符将列名放在后勾中
Schema::table('posts', function (Blueprint $table) {
$table->renameColumn("`content-description`", "content_description");
});
数据库名称中的连字符不好,而且连字符是一个大问题,因为如果最终将列名映射到变量,大多数语言都不喜欢在变量名称中使用连字符 但是您可以将它们与倒勾技巧结合使用,只需将列名括在倒勾(`)中
由于列没有数据,请尝试以下操作
class ModifyColumnName extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn("`content-description`");
$table->string("`content_description`");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->string("`content-description`");
$table->dropColumn("`content_description"`);
});
}
}
根据mariadb.com的说法:“标识符可以使用倒勾字符-``引用。对于不包含特殊字符的标识符,或者对于非保留字的标识符,引用是可选的,如果设置了ANSI_QUOTES SQL_MODE标志,双引号(“)也可以用于引用标识符。”
这就是为什么我更喜欢innoDB…!!始终使用单引号从未见过带有连字符的数据库列名。这不好,但可能是反勾号