CakePHP::ユニークな値かどうかチェック(重複チェック)

4月 15th, 2008 admin Posted in CakePHP | コメントは受け付けていません。

ユーザIDなど重複したら困る時のチェック。よく使うのでメモ
MySQLの場合は、DBのuniqueを使ったスマートな方法もあります。

コード

/model/user.php

PHP:
  1. function unique($field){
  2.        foreach( $field as $key => $value ){
  3.            $this->recursive = -1;
  4.            $found = $this->find(array("{$this->name}.$key" => $value));
  5.         }
  6.            return !$found;
  7.     }

/controller/user_controller.php

PHP:
  1. //省略 addメソッドとか
  2.             if($this->data['User']['username'] && !$this->User->unique(array("username" => $this->data['User']['username']))){
  3.                 $this->User->invalidate("unique");
  4.             }
  5.  
  6.             if ($this->User->save($this->data)) {
  7. //・・・以下省略

/view/user/add.ctp

PHP:
  1. <td width="65%">
  2.         <?php echo $form->input('User/username', array('label' => false)); ?>
  3.         <?php echo $form->error ('User/unique', 'このIDはすでに使用されています。');?>
  4.     </td>

Comments are closed.