LoginSignup
8
6

More than 5 years have passed since last update.

[CakePHP3]DB更新時にNULLをセットするビヘイビア

Posted at

自分が確認した限り(がっつり調べられていない)では、CakePHP3ではVARCHAR型カラムに対して画面の入力フィールドが未入力の場合、NULLではなく空文字がセットされる(バリデーションの設定とかに影響されてそう)。

未入力ならNULLをセットしてほしいのでそれに対応した簡易的なビヘイビアを作成してみました。

これ以外にいい方法があればご教授いただけると幸いです。

cakephp3_behavior_null
<?php
namespace App\Model\Behavior;

use Cake\ORM\Behavior;

/**
 * 各テーブルクラスで、$this->addBehavior('App'); で利用してください
 */
class AppBehavior extends Behavior
{
    function beforeSave($event, $entity, $options) {
        foreach($this->_table->schema()->columns() as $key => $val) {
            if ($entity->get($val) === '') {
                $entity->set($val, NULL);
            }
        }
        return true;
    }
}
8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6