【问题标题】:Changing the Collation of database column is not working in laravel migrations更改数据库列的排序规则在 laravel 迁移中不起作用
【发布时间】:2017-10-05 14:17:19
【问题描述】:

我想更改“users”表中“about_me”列的排序规则。为此,我使用下面的代码。我只是将排序规则更改为utf8mb4_unicode_ci,但代码不起作用。

 public function up()
    {
        if (Schema::hasColumn("users", "about_me")) {
            Schema::table("users", function(Blueprint $table) {
                $table->collation = 'utf8mb4_unicode_ci';
                $table->charset = 'utf8mb4';
            });
        }
 }

我已经在 /config/database.php 中进行了更改,这有助于我将数据保存在 db 中,但是在获取数据库后,我发现特殊符号没有显示,当我将该列的排序规则更改为 utf8mb4_unicode_ci 然后它工作正常。但我想在移民中成功。当前代码不工作,我需要正确的代码。

【问题讨论】:

  • Laravel 支持 MySQL 的每列修改排序规则。您需要在此处编写原始查询来进行表范围的修改

标签: php mysql laravel laravel-5


【解决方案1】:

Laravel 支持修改 MySQL 的每列排序规则。对于表范围的修改,您需要编写原始查询。

public function up()
{

    DB::statement("ALTER TABLE users CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
}

【讨论】:

  • 给出错误:无法访问受保护的属性 $table。但它适用于 {$table->table} => 用户。还有,这里Schema::table没用,可以直接写DB::statement(...)
  • 感谢@ManicDepression 的评论。答案已更新。
【解决方案2】:

在现代 Laravel 中,可以在表或列上设置字符集和排序规则。

https://laravel.com/docs/8.x/migrations#database-connection-table-options

    // You can change table.
    Schema::table('users`', function (Blueprint $table) {
        $table->charset = 'utf8mb4';
        $table->collation = 'utf8mb4_unicode_ci';
    });

    // You can change on a field of a table.
    Schema::table('users', function (Blueprint $table) {
        $table->string('about_me')->charset('utf8mb4')->collation('utf8mb4_unicode_ci')->change();
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-29
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2013-10-25
    • 1970-01-01
    • 2011-04-08
    相关资源
    最近更新 更多