Saving Account Bean breaks Email Relationship

Hello,

I have done extensive research into this problem, and I just can’t figure it out.
I’m syncing data automatically at a set schedule from another system. It syncs Accounts and related Email Addresses.
The problem is, when I save the Account bean, it clears all related email addresses by marking deleted=1 in email_addr_bean_rel table.
Even if I just run this simple code below, it will always clear the oldest email address relationship. The email address table: email_addresses isn’t affected.

$CUSTNMBR = 'MA199';
$bean = new Account();
$bean->retrieve_by_string_fields(array('customercode_c' => $CUSTNMBR));
$bean->save();

Any help or suggestions are greatly appreciated.
Thanks

I got this fixed using a bit of logic to decide wether to add or update a record. I’m using:

$bean = BeanFactory::getBean('Accounts', $bean_existing_cus->id);

for existing records, which keeps the emails addresses as is.

Still have a problem when adding multiple email addresses to a record. When the code below runs, it will clear all existing email address relationships form the record. I end up with just the last email address on the record ?

$bean_email = new SugarEmailAddress;
$bean_email->addAddress($emailAddress);
$bean_email->save($bean_account->id, 'Accounts');