在开发遗留代码库期间,我开始编写一些测试。
测试使用底层sqlite运行。
我遇到了一个问题,一个空的模型值可以很容易地被MariaDB (Prod)或MySQL (临时-ENV)存储,而它在使用sqlite3测试数据库时失败了。
由于表是从迁移中创建的,所以在所有三个系统中都使用相同的配置:
Schema::create('consumers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('type');
$table->string('name', 512);
$table->string('xd_number', 512);
$table->string('guid', 512);
$table->string('country_iso', 2);
$table->string('language_iso', 5);
$table->string('software_version', 128)->nullable();
$table->integer('online_count')->default(0);
$table->integer('download_count')->default(0);
$table->boolean('is_locked')->default(false);
$table->timestamp('locked_at')->nullable();
$table->timestamp('last_online_at')->nullable();
$table->timestamps();
});“生成”数据的php-代码,然后在“空字符串”(可能是从任何地方)填充的数据是这样的:
$consumer = new Consumer();
$consumer->type = $data['type'];
$consumer->xd_number = $login;
$consumer->guid = $this->_createGuid();
$consumer->country_iso = $data['country_iso'];
$consumer->language_iso = $this->_getLanguageIso($request);
$consumer->software_version = $request->input('softwareVersion') ? $request->input('softwareVersion') : null;
$consumer->save();因此,这是模型的一个新实例,name-property从未被调用过。
我还尝试用PhpMyAdmin插入一条记录,使name列为空,尽管它被设置为NULL。
即使这样,PhpMyAdmin也会显示结果查询,将所有空字符串列设置为'' (空字符串):
INSERT INTO `consumers` (`id`, `type`, `name`, `xd_number`, `guid`, `country_iso`, `language_iso`, `software_version`, `online_count`, `download_count`, `is_locked`, `locked_at`, `last_online_at`, `auth_response`, `created_at`, `updated_at`)
VALUES (NULL, '1', '', '', '', '', '', NULL, '0', '0', '0', NULL, NULL, NULL, NULL, NULL);未设置的模型属性作为普通的php类属性返回,调用时为NULL。
我猜对了吗,这意味着NULL-value在保存过程中被转换为''?可能在数据库旁边?
我错过了什么,MySQL和MariaDB都用''替换NULL,但是SQLite试图将NULL插入到本专栏中,并抱怨违反完整性约束的行为。
Integrity constraint violation:
19 NOT NULL constraint failed: consumers.name insert into "consumers" ("type", "xd_number", "guid", "country_iso", "language_iso", "software_version", "updated_at", "created_at")
values (1, FooBar, da55d74c10e1eb31503ec96767268cd0, DE, de-DE, ?, 2022-08-31 00:30:17, 2022-08-31 00:30:17)发布于 2022-10-22 11:43:55
来自MariaDB 文档
如果空值插入到声明为NULL的列中,则将返回一个错误。但是,如果SQL模式不是严格的(默认情况下为MariaDB 10.2.3),则如果空值是插入到声明为NULL的列中的多行值,则将插入列类型的隐式默认值(而不是表定义中的默认值)。隐式默认值是字符串类型的空字符串,数值、日期和时间类型的零值。
这意味着这不是Laravel问题,而是数据库本身。我也有同样的问题,不幸的是,我没有找到SQLite的解决方案,而且看起来也没有。
https://stackoverflow.com/questions/73548847
复制相似问题