chrisnharvey/laravel-sql-require-primary-key

dev-master 2021-03-16 10:20 UTC

This package is auto-updated.

Last update: 2024-09-16 17:58:03 UTC


README

此包是为了解决在使用Laravel的schema builder与强制主键的MySQL服务器(例如DigitalOcean托管数据库)时出现的问题。

问题

此问题发生是因为MySQL中的sql_require_primary_key标志阻止创建没有主键的表。由于Laravel的Schema builder以非序列列分配主键的方式,schema builder将首先创建没有主键的表,然后立即更改表以分配主键。

示例

Schema::create('my_table', function (Blueprint $table) {
    $table->string('id')->primary();
});

对schema builder的上述调用将创建以下查询

create table `my_table` (`id` varchar(255) not null) default character set utf8mb4 collate 'utf8mb4_unicode_ci';
alter table `my_table` add primary key `my_table_id_primary`(`id`);

如果你的MySQL服务器上开启了sql_require_primary_key,你会收到如下错误

SQLSTATE[HY000]: General error: 3750 Unable to create or change a table without a primary key, when the system variable 'sql_require_primary_key' is set. Add a primary key to the table or unset this variable to avoid this message. Note that tables without a primary key can cause performance problems in row-based replication, so please consult your DBA before changing this setting.

解决方案

安装此包将防止此问题发生,同时确保每张表都已设置主键。

它通过监听Laravel的迁移事件,并解析将要运行的查询以检查每张表是否已分配主键,如果发现缺少主键,则抛出异常。

然后暂时禁用sql_require_primary_key,运行迁移,然后恢复sql_require_primary_key到原始值。

安装

此包可以通过composer安装

composer require chrisnharvey/laravel-sql-require-primary-key

如果你已启用自动包发现,那么你已经完成了。否则,你需要注册以下服务提供者

ChrisHavey\LaravelSqlRequirePrimaryKey\ServiceProvider::class

使用方法

将以下配置键添加到你的MySQL数据库配置中。

'require_primary_key' => true

禁用单个迁移的检查

在大多数情况下,你不需要这个,但有时(尤其是与原始查询一起)此包可能无法检测到主键并抛出异常。要禁用这些检查,请将以下属性添加到迁移中

public $skipPrimaryKeyChecks = true;