使用MySQL数据库在Laravel 5.7中进行开发。在我的几个数据库列上,我都有枚举的类型-没有进行研究,而是使枚举充满了数字(0-2或0-3)。在阅读了利弊之后,我想离开枚举并将它们转换为tinyints。
将表中列的类型更改为tinyint并将字符串'0','1','2','3'转换为tinyint的最佳方法是什么?
我真的不想在此过程中丢失数据。
https://laravel.com/docs/5.7/migrations#modifying-columns具有有关修改列的信息,但是它不支持枚举:
仅以下列类型可以“更改”:bigInteger,二进制,布尔值,日期,dateTime,dateTimeTz,十进制,整数,json,longText,mediumText,smallInteger,字符串,文本,时间,unsignedBigInteger,unsignedInteger和unsignedSmallInteger。
答案 0 :(得分:1)
为了安全起见,我会使用临时列进行操作;
ALTER TABLE tbl ADD COLUMN _temp_col CHAR(1) COLLATE 'latin1_general_ci'; -- CHAR(1) is OK if you only have numeric ENUMs
UPDATE tbl SET _temp_col = col; -- ENUM values would be copied as is
ALTER TABLE tbl MODIFY COLUMN col TINYINT(1) UNSIGNED;
UPDATE tbl SET col = _temp_col; -- Values would be auto-converted to ints
ALTER TABLE tbl DROP COLUMN _temp_col;
答案 1 :(得分:0)
使用MySQL-8.0进行实验会产生以下转换。
private function decodeBody($body) {
$rawData = $body;
$sanitizedData = strtr($rawData,'-_', '+/');
$decodedMessage = base64_decode($sanitizedData);
if(!$decodedMessage)
return false;
return $decodedMessage;
}
private function decodeParts($parts)
{
foreach ($parts as $part)
{
if ($part->getMimeType() === 'text/html' && $part->getBody())
if ($result = $this->decodeBody($part->getBody()->getData()))
return $result;
}
foreach ($parts as $part)
{
if ($result = $this->decodeParts($part->getParts()))
return $result;
}
}
/**
* @param Google_Service_Gmail_Message $message
* @return bool|null|string
*/
public function getMessageBody($message)
{
$payload = $message->getPayload();
if ($result = $this->decodeBody($payload->getBody()->getData()))
return $result;
return $this->decodeParts($payload->getParts());
}
似乎转换了ALTER TABLE
-> 'x'
。因此,我想可以根据下面的后续x+1
进行更改
UPDATE
| version() | | :-------- | | 8.0.13 |
select version();
✓
create table x (y enum ('0','1','2','3') );
✓
insert into x values ('1'),('0'),('2'),('3')
| y | | :- | | 1 | | 0 | | 2 | | 3 |
select * from x
✓
alter table x modify y tinyint unsigned;
| y | | -: | | 2 | | 1 | | 3 | | 4 |
select * from x;
✓
update x set y=y-1
| y | | -: | | 1 | | 0 | | 2 | | 3 |
db <>提琴here