使用Zend_Validate_Db_RecordExists进行联合查询

时间:2017-05-16 11:52:49

标签: php mysql zend-framework

我需要在php zend中检查记录是否存在。

我有以下sql查询可以正常工作并提供正确的结果

(SELECT * FROM email where isLogged = 1 and emailId='demo@xyz.com') 
UNION 
(SELECT * FROM email where idPeople = 5 and emailId='demo@xyz.com');

我想使用Zend_Validate_Db_RecordExists编写此查询,以检查在上述条件下是否存在email= 'demo@xyz.com'的记录。

1 个答案:

答案 0 :(得分:0)

我不知道为什么你会为此使用UNION,以下代码应该完成这项工作:

$email     = 'demo@xyz.com';
$clause    = $dbAdapter->quoteIdentifier('isLogged') . ' != 1 OR ' . $dbAdapter->quoteIdentifier('idPeople') . ' != 5';
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table'   => 'email',
        'field'   => 'emailId',
        'adapter' => $dbAdapter,
        'exclude' => $clause
    )
);

if ($validator->isValid($email)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

该代码排除了isLogged != 1idPeople != 5的记录,如果我误解,请告诉我。

编辑:我对UNION vs OR的表现感到好奇,发现这个链接解释了一些细节:https://stackoverflow.com/a/13866221/3784145

相关问题