Implementation of the UUID type field in MySQL table in Laravel 6
1. The database migration implementation is as follows, and an index is added to the UUID type field.
public function up()
{
$tableName = 'theme_installation';
Schema::create($tableName, function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuid('theme_id')->comment('主题ID')->unique();
$table->timestamps();
});
}
2. After the migration is performed, the table field type is char(36). as shown in Figure 1
CREATE TABLE `theme_installation` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`theme_id` char(36) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '主题ID',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `theme_installation_theme_id_unique` (`theme_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
3. In the constructor of the model file, set the field value of the UUID type to: str::OrderDuUID() to take advantage of the sort function. Reference:https://itnext.io/laravel-the-mysterious-ordered-uuid-29e7500b4f8
use Illuminate\Support\Str;
public function __construct(array $attributes = [])
{
$attributes['theme_id'] = Str::orderedUuid();
parent::__construct($attributes);
}
4. Implementation of the actual execution of the model insertion
$themeInstallation = new ThemeInstallation();
$themeInstallation->wp_theme_id = $wpTheme->id;
$themeInstallation->theme_custom_name = $custom_name;
$themeInstallation->save();
5. Error during execution: add[theme_id]To Fillable Property To Allow Mass Assignment On[Modules\\ThemeStoreDB\\Entities\\ThemeInstallation]… as shown in Figure 2
{
"message": "Add [theme_id] to fillable property to allow mass assignment on [Modules\\ThemeStoreDB\\Entities\\ThemeInstallation].",
"status_code": 500,
"debug": {
"line": 332,
"file": "E:\\wwwroot\\object\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Eloquent\\Model.php",
"class": "Illuminate\\Database\\Eloquent\\MassAssignmentException",
"trace":
}
}
6. Set the Theme_ID attribute of the model can be assigned in batches
protected $fillable = ['theme_id'];
7. The final generated SQL is as follows, which is in line with expectations. as shown in Figure 3
insert into
`table` (
`theme_custom_name`,
`role`,
`processing`,
`processing_failed`,
`theme_id`,
`theme_store_theme_id`,
`wp_theme_id`,
`updated_at`,
`created_at`
)
values
(
'',
'unpublished',
1,
0,
'966165f6-139a-464d-b2aa-77af8bc32a4a',
9,
88,
'2022-05-25 11:51:06',
'2022-05-25 11:51:06'
)

![执行时报错:Add [theme_id] to fillable property to allow mass assignment on [Modules\\ThemeStoreDB\\Entities\\ThemeInstallation].](https://www.shuijingwanwq.com/wp-content/uploads/2022/08/2.png)
