symfony フレームワークを使用して、データベース テーブルにクエリを実行してエントリが既に存在するかどうかを確認するのに最適なコードはどれですか?
次のようなクエリが必要です。
$q = $this->createQuery('t')
->where('t.email = ?', $email)
->andWhere('t.type = ?','newsletter');
symfony フレームワークを使用して、データベース テーブルにクエリを実行してエントリが既に存在するかどうかを確認するのに最適なコードはどれですか?
次のようなクエリが必要です。
$q = $this->createQuery('t')
->where('t.email = ?', $email)
->andWhere('t.type = ?','newsletter');
Doctrine_Table インスタンスにいると仮定すると、最も簡単な方法は次のとおりです。
$this->findOneByEmail($email);
type
具体的な継承を使用している場合は、DQL コールバックを介して追加されるため (それらが有効になっていると仮定して)、必要ありませんが、完全を期すために:
$this->findOneByEmailAndType($email, 'newsletter');
存在する場合は Doctrine_Record を返し、存在しない場合は null を返します。
クエリでカウントを使用することもできます。
$exists = $this->createQuery('t')
->where('t.email = ?', $email)
->andWhere('t.type = ?','newsletter') // your probably don't need this
->count();
これにより、クエリに一致するレコードの数が返されます。これは、結果を水和させないため、より効率的です。
これを試して、
フォームクラスで直接定義できます。
$this->validatorSchema['email'] = new sfValidatorAnd(array(
new sfValidatorString(array('required' => true, 'trim' => true)),
new sfValidatorDoctrineUnique(array('model'=>'User','column'=>'email'),
array('invalid' =>'Email Address already exist')),
new sfValidatorRegex(
array('pattern' => '~^(\s)*[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})(\s)*$~i'),
array('invalid' => 'Please enter valid email ID'))),
array(),
array('required' =>'Please enter email ID')
);
他よりずっと簡単だと思います。