是否可以在laravel迁移中更改mysql DB编码字符集?

fan*_*tly 3 php mysql eloquent laravel-5

我试图改变Laravel-5中mysql数据库的编码,我尝试过迁移,遵循这个例子:https://slashdot.io/blog/adding-emoji-support-to-your-blog -948181198 - 但是,没有任何更新,并且charset /编码保持不变.

是否可以通过迁移执行此操作?或者我是否必须编写单独的脚本?

迁移(完整性)

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    DB::raw('ALTER TABLE homestead.survey_responses CONVERT TO CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci');
    DB::raw('REPAIR TABLE homestead.survey_responses');
    DB::raw('OPTIMIZE TABLE homestead.survey_responses');
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    DB::raw('ALTER TABLE homestead.survey_responses CONVERT TO CHARACTER SET = utf8 COLLATE utf8_unicode_ci');
    DB::raw('REPAIR TABLE homestead.survey_responses');
    DB::raw('OPTIMIZE TABLE homestead.survey_responses');
}
Run Code Online (Sandbox Code Playgroud)

上面的迁移运行没有错误,但遗憾的是什么也没做.

Cra*_*rld 9

Big necro here.

Laravel 7 comes out of the box with functionality to change the charset and collation on a table. I needed this for Cashier/stripe.

The documentation shows you how to do it here

Schema::create('users', function (Blueprint $table) {
    ....
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_bin';
});
Run Code Online (Sandbox Code Playgroud)

Edit

Alternatively, and a better solution for me was to change the collation on a single column.

$table->string('name')->collation('utf8mb4_bin');
Run Code Online (Sandbox Code Playgroud)


jed*_*ylo 6

使用通常在迁移类中使用的Schema/Blueprint类是不可能的.但是你仍然可以使用DB facade 运行你需要的任何SQL - 在你的情况下:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class ChangeCharsetAndCollation Migration
{
    public function up()
    {
        DB::statement('ALTER DATABASE database CHARACTER SET new_charset COLLATE new_collation');
    }

    public function down()
    {
        DB::statement('ALTER DATABASE database CHARACTER SET old_charset COLLATE old_collation');
    }
}
Run Code Online (Sandbox Code Playgroud)

只需用所需的值替换database,old_charset,old_collat​​ion,new_charset,new_collat​​ion,并确保您的用户有权运行此类查询.

  • 谢谢你的帮助:)看到这个是正常的:[Illuminate\Database\QueryException] SQLSTATE [HY000]:一般错误:2014当其他无缓冲的查询处于活动状态时,无法执行查询.考虑使用PDOStatement :: fetchAll().或者,如果您的代码只是针对mysql运行,则可以通过设置PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY属性来启用查询缓冲.(SQL:ALTER DATABASE homestead CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci)? (4认同)