Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

After studying this topic, you should be able to:

  • Describe how objects, fields, relationships can be used to define an appropriate data model for an application
  • Identify the different types of objects, fields, relationships to determine how and when then can be used in a requirement
  • Understand what external IDs are how they can be used to build a solution that involves external data

Table of Contents

  • Data Modeling
  • Relationships
  • Lookup Relationships
  • Master-Detail Relationships
  • Many-to-Many Relationships
  • External IDs
  • External Relationships
  • Hierarchical Relationships
  • Custom Settings
  • Modification Considerations
  • Data Modeling Tools
  • Schema Builder
  • Accessing Data Model Using Apex
  • Schema Namespace: Classes and Methods
  • Accessing Data Model Example
  • Platform Events
  • Scenarios and Solutions

Introduction - Salesforce Data Model

  • “Building an efficient data model requires effective knowledge on the different types of objects, fields, and relationships offered by the platform as well as their limitations, features, and characteristics.”
    • Standard Objects: Standard objects such as Account, Contact, Lead, and Opportunity are included in Salesforce by default
    • Lookup Relationships: Two different objects can be linked such that there is no effect on deletion or security of records
    • Master-Detail Relationships: Two different objects can be linked such that child records are deleted automatically with parent records
    • Many-to-Many Relationships: A record of one object an be related to multiple records of another object and vice versa using a junction object
    • Custom Objects: Custom objects can be created to store specific information that cannot be stored in standard objects
    • Standard Fields: Standard fields such as Name, ID, and CreatedDate are created by default
    • Custom Fields: Create custom fields of different data types to store additional information
    • Data Model: Objects, fields, and relationships can be created in Salesforce to represent the data in the database

Data Modeling

  • Schema Builder allows viewing and setting up the data model quickly and efficiently
  • A data model is a way to represent data in a database consisting of tables with columns and rows
    • Objects represent tables, fields represent columns, records represent rows
    • A data model can represent a collection of objects and fields in an app and how they are related to one another
    • Relationships: two objects can be linked to each other using a relationship field. The type of relationship depends on factors such as object type, security, and deletion
  • Custom Field Types:
    • Number (supports external ID), Percent, Currency, Date and Time (Ex: Date, Date/Time, Time), Relationship (Standard Lookup, External Lookup, Master-Detail), Rollup Summary (read-only), Auto-Number (read-only, supports external ID), Formula (read-only), Phone, Email (supports external ID), Geolocation (compound field containing latitude and longitude, respectively), URL, Text (Text, Text (encrypted), Text Area, Text Area Long, Text Area Rich), Checkbox, Picklist (Standard, Multi-Select)

Relationships

  • Types of relationships that are available:
    • Lookup: objects are loosely coupled, independent sharing settings and deletion
    • Master-Detail: objects are tightly coupled, dependent sharing settings and deletion
    • Many-to-Many: require a third object, records of one object can be related to multiple records of another, and vice versa
    • External Lookup: involve an external object, link a child standard, custom, external object to a parent external object using the standard external ID field
    • Indirect Lookup: link a child external object to a parent standard or custom object through a custom unique External ID field
    • Hierarchical: create a lookup to associate one user with another that does not directly or indirectly refer to itself

Lookup Relationships

  • Loose connection:
    • Parent and child objects have independent sharing settings
    • Parent can be prevented from being deleted if children exist
    • Related list: records of the child can be made to appear in a related list on the parent record
    • Lookup relationship fields can be required or optional
    • Lookup Filter: can be defined to limit which records can be used as parent records
    • One-to-Many: Ex: “Store” object related to a “Sales Order” object
    • Self-Relationship: Ex: “Contact” could have an “Assistant” lookup back to “Contact”
  • Standard Report Types are automatically created when new lookup relationships are created

Master-Detail Relationships

  • Close/Tight connection:
    • Detail records inherit the sharing and security settings of the master
    • Deleting the master record automatically deletes the detail records
    • Master-detail relationship field is always required on the detail records
    • Reparenting detail records can be enabled or disabled
    • Roll-up summary fields can be created on the master object to summarize the detail records
  • Each object can have up to two master-detail relationships
  • By default, cannot reparent records, but administrators can “Allow Reparenting”
  • Custom objects on the detail side of a master-detail relationship are unable to use sharing rules, manual sharing, or queues, since the Owner field is shared with the Master
  • Lookups must be on the page layout of detail and sub-detail records
  • Reporting:
    • Master-detail relationships allow data from three objects to be joined in one report: master, detail, and one other lookup object
    • If detail object has multiple lookups, a separate report type is available based on each lookup
    • Relationships to be included in the report type can be selected, along with the option to include records that have a detail record or not

Many-to-Many Relationships

  • Many-to-many relationships allow two objects to be related to each other when a record from one object can be linked to multiple records from another object, and vice versa
    • Master record can have multiple detail records
    • Detail records can have multiple master records
    • Junction Objects sit in between the two objects to be related
    • Ex: consider “Job,” “Applicant,” and “Job Application” objects. “Job Application” would be the junction object.
  • In Reports, the master object listed first determines the scope of records in the report

External IDs

  • External IDs are fields that contain a unique identifier from a system outside of Salesforce
    • Unique ID setting is often enabled so that External ID values are unique to each record in Salesforce
    • Ex: “SAP Account Number” field could be added to the “Account” object and marked as an External ID
  • Up to 25 External ID fields per object
  • Field Types: number, text, or email

External Relationships

  • External lookup allows linking a child standard, custom, or external object with a parent external object
    • Enabled by Salesforce Connect
    • External lookup relationships allow referencing data outside of the Salesforce organization
  • External object field values come from an external data source
  • Ex: an external object called “Orders” could be related to standard object “Account”
  • Indirect Lookup allows linking a child external object with a parent standard or custom object
    • Enabled by Salesforce Connect
    • Parent object field and the child object field is specified to match and associate records in the relationship
    • Ex: Account object is linked with external Order object using an indirect lookup relationship
    • In an indirect lookup, the external column name and a unique external id field are used for matching and associating the records
  • Implications of External and Indirect Lookup Relationships:
    • Only lookup, external lookup, and indirect lookup relationships are available for external objects
    • Related lists: loading of related lists of child external objects could be impacted if external systems availability is impacted

Hierarchical Relationships

  • Hierarchical relationships allow relating one user to another
    • Usable on the User object only
    • Ex: can store a User’s Manager or Team Leader

Custom Settings

  • Custom Settings enable application developers to create custom sets of data for an organization, profile, or specific user:
    • Cache: application cache enables efficient access to custom settings, avoiding repeated queries to the database
    • Uses: can be used by formula fields, validation rules, flows, Apex, and the SOAP API
    • Access: via custom setting methods or the $Setup variable
    • List Custom Setting: can only be accessed using Apex or API calls
    • Query: custom settings can be queried like a custom object

Modification Considerations

  • Behavior of objects and fields change when they are referenced in Apex and Visualforce pages:
    • Custom objects referenced in Apex code/Visualforce page cannot be deleted
    • Apex uses the field’s API name, so the label can change after field creation
    • SOQL Query Results depend on the design of the data model and relationships
    • Apex code that references a relationship needs to be updated if the relationship is modified
    • Custom fields referenced in Apex code/Visualforce page cannot be deleted
    • Custom fields referenced in Apex code/Visualforce pages cannot be changed
    • If a new value is added to a picklist, logic used in Apex code may need to be updated. Modifying length/decimal place of a field may cause data loss

Data Modeling Tools

  • Apex code can be sued to access the data model programmatically, similar to using the object manager or schema builder
  • Object Manager and Schema Builder can be used to access the data model and create new functionality

Schema Builder

  • Can be used to efficiently create a number of objects, fields, and relationships - requires much less time than using the Object Manager

Accessing Data Model Using Apex

  • sObject is a representation of any Salesforce record - can be accessed using tokens or the describeSObjects Schema method
    • describe information: provides metadata about sObject and field properties
    • Supported Operations: operations supported by an sObject like create or undelete can be determined
    • Object information like an sObject’s name, label, fields, and child objects can be retrieved
    • describe information provides details about objects, not records
    • Describing Information require a token, describe result object, and describeSObjects are used to get describe information
  • Two data structures and a Schema method are used for accessing sObject and field describe information in Apex:
    • getSObjectType method: sObjectType member variable
    • getSObjectField method: static member variable name
    • DescribeSObjectResult class: provides methods for describing sObjects
    • DescribeFieldResult class: provides methods for describing fields
    • getDescribe method: used to access the describe result
    • describeSObjects schema method: used to describe sObjects by passing one or more sObject type names

Schema Namespace: Classes and Methods

Reference FoF Slides

Accessing Data Model Example

  • How to retrieve sObject metadata programmatically:
// get a map of all the standard and custom objects
Map<String, Schema,SObjectType> allObjects = Schema.getGlobalDescribe():
System.debug(allObjects);
// get metadata of one object
Schema.DescribeSObjectResult[] results = Schema.describeSObjects(new String[] {'Account'});
For (Schema.DescribeSObjectResult result : results) {
    System.debug('sObject Label: ' + result.getLabel()); // get label of object
    System.debug('Number of fields: ' + result.fields.getMap().size()); // get field count
    // Check if object is standard or custom
    System.debug('Standard object: ' + (result.isCustom() ? 'No' : 'Yes'));
}
  • Get App Metadata Programmatically
String appName = 'Service'; // get info about this app

// get tabset for each app in the org
List<Schema.DescribeTabSetResult> tabSetDesc = Schema.describeTabs();

// loop through each result and display information for a specific app
for (Schema.DescribeTabSetResult tsr : tabSetDesc) {
    if (tsr.getLabel() == appName) {
        System.debug('Logo URL: ' + tsr.getLogoUrl());
        System.debug('Namespace: ' + tsr.getNamespace());
        System.debug('Number of tabs: ' + tsr.getTabs().size());
    }
}
  • Check Object Permissions of Current User
// do something if current user can access email field of contact record
if (Schema.SObjectType.Contact.fields.Email.isAccessible()) {
    // Check if user can access email field
    System.debug('You may send an email!');
}
// do something if current user has permission to delete a contact record
if (Schema.SObjectType.Contact.isDeletable()) {
    System.debug('You may delete this record!');
} else {
    System.debug('You are unable to delete this record.');
}

Platform Events

  • Platform events are similar to custom objects and are defined in the same way. Here are the differences between them:
Custom Object Platform Event
Instance is called a record Instance called an event message
API name ends with “__c API name ends with “__e
Records can be inserted, updated, deleted Event messages can be inserted only
Records can be viewed in the UI Event messages cannot be viewed in the UI
Records can be queried using SOQL/SOSL Event messages cannot be queried using SOQL/SOSL
Supports all field types Limited subset of field types
Records are retained indefinitely until deleted Event messages expire after 72 hours
  • Platform events are used to deliver near real-time notifications in the Salesforce platform or an external application
  • Platform events us an event-driven architecture:
    • Event Producer: publishes an event message over a channel
    • Channel (IE event “bus”): conduit through which the event message is transmitted
    • Event Consumer: subscribes to the channel and receives the event message
  • Event: any meaningful change in a business process - Ex: a user changes the stage of an opportunity to “Closed Won”
  • Event Message: a notification that contains data about the event - published when an event occurs
  • Example: Salesforce publishes a custom platform event message over a channel when the stage of an opportunity changes to “Closed Won.” An order management system subscribed to the channel receives the message to create an order.

  • Defining Platform Events
    • Platform events need to be defined before event messages can be published. Custom platform events are sObjects and defined like a custom object:
      • Navigate to: Setup > Quick Find > “Platform Events” > Platform Events
      • Define them by giving a name and adding custom fields
        • Example name: Opportunity_Event__e
        • ReplayId: refers to the position of the event in the event stream
        • EventUuid: identifies an event message and can be used to determine whether the message was successfully delivered
        • Possible fields: Checkbox, Date, Date/Time, Number, Text, Text Area (Long)
      • Select a Publish Behavior:
        • Publish After Commit: publish the platform event only if a transaction commits successfully
        • Publish Immediately: otherwise
    • Standard Platform Events are predefined platform events such as AssetTokenEvent and BatchApexErrorEvent

  • Platform Event Support
    • Event messages can be **published from Salesforce using processes, flows, or Apex
    • Possible to subscribe to and receive platform events using processes, flows, Apex triggers, and custom Lightning components
    • Processes, flows, and triggers provide an auto-subscription mechanism
    • In a Lightning component, empApi component can be used for subscription and receiving event messages
  • External apps
    • External apps can use any Salesforce API to publish event messages, including SOAP API, REST API, or Bulk API
    • Ex: to publish a platform event message for a plaatform event named Opportunity_Event__e using REST API, a POST can be sent to: /services/data/v48.0/sobjects/Opportunity_Event__e
  • Bayeux protocol is required in order to subscribe to platform events in an external app

Scenarios and Solutions

Reference FoF Slides