クエリの条件として電子メール アドレスを使用して、見込み客と連絡先に対してクエリを実行する必要があります。見込み客のレコードが 0 件、連絡先のレコードが 0 件返された場合は、新しい見込み客を作成します。
クエリは、見込み客または連絡先のいずれかに対して複数のレコードを返す可能性があるため、そのケースを処理するための戦略を開発する必要があります。メールアドレスは一意である必要はありません。
public class StackOverflowExample {
public static void test(String email) {
handleNewEmail(email);
}
private static void handleNewEmail(String email) {
List<Lead> leads = [select id, email from Lead where email = :email];
List<Contact> contacts = [select id, email from Contact where email = :email];
if (leads.size() == 0 && contacts.size() == 0) {
//Create new lead
insert new Lead(Company = 'Lead Company', FirstName = 'firstname', LastName = 'lastname', Email = email);
} else if (leads.size() == 1) {
// Update this lead
leads[0].FirstName = 'newfirstname';
update leads;
} else if (contacts.size() == 1) {
// Update this contact
contacts[0].FirstName = 'newfirstname';
update contacts;
} else {
// Must be more than 1 contact or lead
System.debug('\nMore than 1 contact or lead.');
}
}
}
もう 1 つのオプションは、範囲を電子メール フィールドに限定して検索を実行することです。
public class StackOverflowExample {
public static void test(String email) {
handleNewEmail(email);
}
private static void handleNewEmail(String email) {
List<List<SObject>> searchResults = [FIND :email IN Email Fields RETURNING
Lead(Id, FirstName, LastName),
Contact(Id, FirstName, LastName)];
List<Lead> leads = ((List<Lead>)searchResults[0]);
List<Contact> contacts = ((List<Contact>)searchResults[1]);
if (leads.size() == 0 && contacts.size() == 0) {
//Create new lead
insert new Lead(Company = 'Lead Company', FirstName = 'firstname', LastName = 'lastname', Email = email);
} else if (leads.size() == 1) {
// Update this lead
leads[0].FirstName = 'newfirstname';
update leads;
} else if (contacts.size() == 1) {
// Update this contact
contacts[0].FirstName = 'newfirstname';
update contacts;
} else {
// Must be more than 1 contact or lead
System.debug('\nMore than 1 contact or lead.');
}
}
}