Inserting NULL into NOT NULL columns with Default Value

后端 未结 5 1102
没有蜡笔的小新
没有蜡笔的小新 2021-02-15 06:36

For a bit of background, we use Zend Framework 2 and Doctrine at work. Doctrine will always insert NULL for values we do not popul

5条回答
  •  无人共我
    2021-02-15 07:16

    MySQL actually works as intended, and that behavior seems to be there to stay. MariaDB also works the same way now.

    Removing "strict mode" (STRICT_TRANS_TABLES & STRICT_ALL_TABLES) is supposed to revert to the previous behavior, but I personally haven't had any luck with it (maybe I'm doing something wrong, but both my @@GLOBAL.sql_mode & @@SESSION.sql_mode do not contain strict mode).

    I think the best solution to this problem is to rely on default values at the PHP level, instead of relying on the Database to provide them. There is an existing answer that explains it pretty well. The comments are also helpful.

    That way, you also gain the added benefit that your models/entities will have the default value upon instantiation instead of upon insert in the database. Also, if you want to surface those values to the user after insertion, you can do so without having to do an extra SELECT query after your INSERT.

    Another alternative to surface the default values would be to use a RETURNING clause, as is available in PostgreSQL, but not in MySQL (yet). It might be added at some point in the future, but for now MariaDB only has it for DELETE statements. However, I believe that having the default values at the PHP level is still superior; even if you never insert the record, it'll still contain the default values. I've never turned back and used a database default value since putting this into practice.

提交回复
热议问题