在 Laravel 6 中,MySQL 表中使用 UUID 类型字段的实现
1、数据库迁移实现如下,在 UUID 类型字段上添加了索引。
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、执行迁移后,表字段类型为 char(36)。如图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、在模型文件的构造方法中设置 UUID 类型的字段值为:Str::orderedUuid(),以利用排序功能。参考: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、在实际执行模型插入时的实现
$themeInstallation = new ThemeInstallation(); $themeInstallation->wp_theme_id = $wpTheme->id; $themeInstallation->theme_custom_name = $custom_name; $themeInstallation->save();
5、执行时报错:Add [theme_id] to fillable property to allow mass assignment on [Modules\\ThemeStoreDB\\Entities\\ThemeInstallation].。如图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、设置 模型的 theme_id 属性可以批量赋值
protected $fillable = ['theme_id'];
7、最终生成的 SQL 如下,符合预期。如图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)

近期评论