我的回答与laravel相关
我在mysql中有表。我发现有些列在插入时没有通过。 mysql 如何接受插入这些记录而不抛出异常?
当我插入行而不向它们传递值时,这些列会向它们添加零值。
这是表架构
create table if not exists ads_sliders
(
id bigint unsigned auto_increment
primary key,
name varchar(191) not null,
image varchar(191) not null,
appearance_time int default 0 null,
active tinyint(1) default 1 not null,
`default` tinyint(1) default 0 null,
first_period_sort int default 99 null,
second_period_sort int default 99 null,
third_period_sort int default 99 null,
internal_link varchar(191) null,
external_link varchar(191) null,
deleted tinyint(1) default 0 not null,
country_id char(36) not null,
created_at timestamp null,
updated_at timestamp null,
start_date date not null,
end_date date not null,
ad_appears smallint default 1 null,
display_period int unsigned not null,
repetition int unsigned not null,
display_place tinyint not null,
on_click_action tinyint not null,
data json null,
constraint ads_sliders_country_id_foreign
foreign key (country_id) references countries (id)
on delete cascade
)
collate=utf8mb4_unicode_ci;
这是插入语句
insert into
`ads_sliders` (
`name`,
`image`,
`country_id`,
`end_date`,
`updated_at`,
`created_at`
)
values
(
'sadf',
'assets/images/ads_sliders/cLZVRNXf0LAP4j3IsdLImZejouAEri0grvEJxB0S.png',
'55af3f40-23e3-11e9-acdc-efd87e16b684',
'2024-04-30',
'2024-04-30 09:16:07',
'2024-04-30 09:16:07'
)
我已经仔细检查过这些列不为空并且没有默认值。我确保全局 sql_mode 变量值是默认值,即 ONLY_FULL_GROUP_BY、STRICT_TRANS_TABLES、NO_ZERO_IN_DATE、NO_ZERO_DATE、ERROR_FOR_DIVISION_BY_ZERO、NO_ENGINE_SUBSTITUTION。 mysql版本是8.0.
我在新的数据库模式中测试它。并且它工作正常。 在此输入图片描述
在 MySQL 中,如果您尝试在表中插入一行而不为每列指定值,数据库将通过以下方式之一处理它:
因此,如果您看到插入记录时没有显式提供所有列的值,则可能是由于以下原因之一造成的。您可以检查表架构中的列定义,以查看是否定义了默认值或者列是否允许 NULL 值。另外,您可以检查 SQL 模式是否设置为 strict。
不允许可为空值和不声明默认值并不是很常见的做法。定义这些取决于您的应用程序的具体要求以及您正在处理的数据的性质。但我确实建议您在不允许 null 时声明默认值,并且在插入时也不要传递值。
很抱歉,这是 Laravel 的问题。我在执行请求时测试了它。 在此输入图片描述
当请求在某个地方执行时,sql_mode 变量在会话阶段发生了变化。
我去了mysql连接内的database.php配置文件,你会看到有严格模式。
如果您将其关闭。每当 Laravel 与数据库建立任何连接时,它都会将 sql_mode 更改为 NO_ENGINE_SUBSTITUTION。 在这种情况下,惰性语句中任何缺失的值都将被忽略。