Laravel迁移回滚错误,列数据太长

问题描述 投票:3回答:2

我使用的是Laravel 5.3,迁移对于控制数据库开发来说非常棒。

我的问题是当我将列类型从字符串更改为文本时,一切都运行良好。但是在用户保存长度超过255(varchar)的数据之后。然后我的迁移无法回滚。它会说数据太长了我的专栏。想问大家如何解决这个问题?

=========================================================

Schema::table('tbname', function(Blueprint $table)
{
    $table->text('value')->change();
});

Schema::table('tbname', function(Blueprint $table)
{
    $table->string('value')->change();
});

=========================================================

播种机:

$records = [
    [
        'description' => 'The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. '
    ],
    [
        'description' => 'The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. The description is longer than 255. '
    ]
];

foreach ($records as $index => $record) {
    Desc::create($record);
}
php mysql laravel laravel-5.3 laravel-5.4
2个回答
9
投票

你有一个text字段,其中包含超过255个字符。在回滚中,您尝试将字段更改为varchar(255)。此时,MySQL决定:要么截断数据以适应255个字符,要么抛出错误。

如果在严格模式下使用MySQL,MySQL将抛出错误。如果不使用严格模式,MySQL将截断数据而不会出错。

Laravel 5.3默认更改为使用严格模式。

如果要停止收到此错误,可以通过在'strict' => false文件中设置config/database.php来禁用严格模式。

请注意,虽然这将抑制错误,但会产生后果。之前导致此错误的数据现在只会被截断而不会出现任何错误。

如果您只想为回滚禁用严格模式,则可以创建第二个禁用严格模式的数据库连接,并告知您的迁移使用该连接进行回滚。但请记住,这将截断此字段中超过255个字符的所有数据。

配置:

'connections' => [
    'mysql' => [
        /* normal connection information */
        'strict' => true,
    ],
    'mysql-rollback' => [
        /* normal connection information */
        'strict' => false,
    ],
],

移民:

public function down()
{
    Schema::connection('mysql-rollback')->table('tbname', function(Blueprint $table) {
        $table->string('value')->change();
    });
}

1
投票

Laravel字符串类型在数据库中创建varchar列。 VARCHAR列中的值是可变长度字符串。长度可以指定为MySQL 5.0.3之前的0到255之间的值,5.0.3及更高版本中的0到65,535之间的值。 MySQL 5.0.3及更高版本中VARCHAR的有效最大长度取决于最大行大小(65,535字节,在所有列之间共享)和使用的字符集。

而不是使用字符串使用text数据类型。因为你运行的mysql版本低于MySQL 5.0.3。

© www.soinside.com 2019 - 2024. All rights reserved.