0

使用 symfony 框架,哪个代码最好查询数据库表以检查条目是否已经存在?

我需要这样的查询:

$q = $this->createQuery('t')
    ->where('t.email = ?', $email)
    ->andWhere('t.type = ?','newsletter');
4

2 回答 2

3

假设您在 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();

这将返回与查询匹配的记录数。这更有效,因为它不会使结果水合。

于 2011-03-04T11:27:30.927 回答
1

试试这个,

您可以直接在表单类中定义。


$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')
);

我认为它比其他容易得多。

于 2011-03-16T10:41:23.863 回答