CakePHP3 bakeで自動生成されたEntity(モデル)について。
● 使用例のテーブル定義(usersテーブル)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // ユーザーテーブル // status 0:仮登録 1:本登録 2:退会 CREATE TABLE `users` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `status` char(1) DEFAULT 0, `created` DATETIME DEFAULT NULL, `modified` DATETIME DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; // テストデータ INSERT INTO `users` (`id`, `email`, `password`, `status`, `created`, `modified`) VALUES (NULL, '001@cakephp3.com', '001', '0', NULL, NULL), (NULL, '002@cakephp3.com', '002', '1', NULL, NULL); |
◯ bakeコマンド実行で作成されるEntityファイル(Model/Entity/User.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # cat src/Model/Entity/User.php <?php namespace App\Model\Entity; use Cake\ORM\Entity; /** * User Entity * * @property int $id * @property string $email * @property string $password * @property string $status * @property \Cake\I18n\FrozenTime $created * @property \Cake\I18n\FrozenTime $modified */ class User extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * * @var array */ protected $_accessible = [ 'email' => true, 'password' => true, 'status' => true, 'created' => true, 'modified' => true ]; /** * Fields that are excluded from JSON versions of the entity. * * @var array */ protected $_hidden = [ 'password' ]; } |
◯ $_accessible解説
1 2 3 4 5 6 7 8 9 | // trueとfalseの値はそれぞれ、その列が一括代入(patchEntity)できるか、できないかを示しています。 // falseだとpatchEntityしても値セットされない。 protected $_accessible = [ 'email' => true, 'password' => true, 'status' => true, 'created' => true, 'modified' => true ]; |
◯ $_hidden解説
1 2 3 4 5 | // JSON、配列フォーマットで出力したくないフィールドを設定する。 // $this->Users->get(ユーザーID); で取得した際、passwordカラムは取得されない。 protected $_hidden = [ 'password' ]; |