yii2-gii icon indicating copy to clipboard operation
yii2-gii copied to clipboard

Default value with string rule should be null (if allowed in Schema) or exception (if not) same as with integer one

Open yii-bot opened this issue 7 years ago • 1 comments

This issue has originally been reported by @6562680 at https://github.com/yiisoft/yii2/issues/16909. Moved here by @cebe.


What steps will reproduce the problem?

Create table1, add varchar(100) field, set NOT NULL for the field Create table2, add varchar(100) field, DO NOT set NOT NULL field, add foreign key to table1 (data can be null, because foreign key) Build models Try to insert/update model2

What is the expected result?

Null value in model2 field

What do you get instead?

Empty string value in model2 field what causes Foreign key exception

Additional info

Q A
Yii version 2.0.14
PHP version 7.2
Operating system Windows 10 Pro

yii-bot avatar Nov 27 '18 11:11 yii-bot

Here are DDLs for the tables:

CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT;

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_t1_name` (`name`),
  CONSTRAINT `fk_t1_name` FOREIGN KEY (`name`) REFERENCES `t1` (`name`)
) ENGINE=InnoDB DEFAULT;

The following code produces an error:

$t2 = new T2();
$t2->name = '';
$t2->save();

But the following code works correctly:

$t2 = new T2();
$t2->save();

$t2 = new T2();
$t2->name = null;
$t2->save();

So, I think everything works as expected. Is it fixed already?

alexkart avatar Feb 18 '19 13:02 alexkart