Fetching Relationships

Overview

The SugarBean class supports fetching related information from the database.
To fetch related records, you will need to load the relationship using the link.
//If relationship is loaded
if ($bean->load_relationship($link))
{
    //Fetch related beans 
    $relatedBeans = $bean->$link->getBeans();
}
An example of this is to load the contacts related to an account:
//Load Account
$bean = BeanFactory::getBean('Accounts', $id);

//If relationship is loaded
if ($bean->load_relationship('contacts'))
{
    //Fetch related beans 
    $relatedBeans = $bean->contacts->getBeans();
}

Fetching a Parent Record

Fetching a parent record is very similar to fetching child records in that you will still need to load the relationship using the link.
//If relationship is loaded
if ($bean->load_relationship($link))
{
    //Fetch related beans 
    $relatedBeans = $bean->$link->getBeans();
   
    $parentBean = false;
    if (!empty($relatedBeans))
    {
        //order the results
        reset($relatedBeans);
       
        //first record in the list is the parent
        $parentBean = current($relatedBeans);
    }
}
An example of this is to load a contact and fetch its parent account:
//Load Contact
$bean = BeanFactory::getBean('Contacts', $id);

//If relationship is loaded
if ($bean->load_relationship('accounts'))
{
    //Fetch related beans 
    $relatedBeans = $bean->accounts->getBeans();    

    $parentBean = false;
    if (!empty($relatedBeans))
    {
        //order the results
        reset($relatedBeans);
       
        //first record in the list is the parent
        $parentBean = current($relatedBeans);
    }
}