我需要确保电子邮件字段对于当前联系人表是唯一的,并且我想确保同一电子邮件对于用户表也是唯一的。如果在任一表中均未找到,则允许保存数据。
我不确定我是否以最佳方式检索数据。这是我发现工作的唯一方法。
此外,我可以让自定义检查工作,如果电子邮件存在,它将返回 false,如果电子邮件不存在,它将返回 true,但它仍会保存数据。如果找到电子邮件,不知道如何告诉它不要保存数据。
这是我目前的联系人表模型:
<?php
namespace App\Model\Table;
use App\Model\Entity\Contact;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
/**
* Contacts Model
*/
class ContactsTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('contacts');
$this->displayField('first_name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->allowEmpty('id', 'create');
$validator
->add('email', [
'validateEmail' => [
'rule' => 'validateEmail',
'provider' => 'table',
'message' => 'That email already exists'
]
])
->requirePresence('email', 'create')
->notEmpty('email');
return $validator;
}
//check that the email is unique in both the Contacts table and in the Users table
public function validateEmail($value, $context) {
$usersTable = TableRegistry::get('Users');
$contactsTable = TableRegistry::get('Contacts');
if ( $contactsTable->exists(['email' => $value]) || $usersTable->exists(['email' => $value]) ) {
return false;
} else {
return true;
}
}
}