+44 (203) 695-03-80
« Back to List

ORM (How to Manage Entities)

EspoCRM has built-in own ORM (Object-relational mapping). It’s very simple to create, update, read, delete and search entities. All these operations available through EntityManager object. EntityManager is available in record Services by method #getEntityManager().

$entityManager = $this->getEntityManager();

Create new entity

$account = $entityManager->getEntity('Account')

or

$account = $entityManager->getRepository('Account')->get();

Fetch existing

$account = $entityManager->getEntity('Account', $accountId);

or

$account = $entityManager->getRepository('Account')->get($accountId);

Get value

$fieldValue = $account->get('fieldName');

Has value

$fieldNameIsSet = $account->has('fieldName'); // true or false

Set value

$account->set('fieldName', 'Test Account');
$account->set(array(
  'name' => 'Test Account',
  'assignedUserId' => '1'
));

Store

$entityManager->saveEntity($account);

or

$entityManager->getRepository('Account')->save($account);

Remove

$entityManager->removeEntity($account);

or

$entityManager->getRepository('Account')->remove($account);

Find

$accountList = $entityManager->getRepository('Account')->where(array(
    'type' => 'Customer',    
))->find();

Descending order:

$accountList = $entityManager->getRepository('Account')->limit(0, 10)->order('createdAt', true)->find();

Ascending order:

$accountList = $entityManager->getRepository('Account')->limit(0, 10)->order('createdAt')->find();

or:

$accountList = $entityManager->getRepository('Account')->limit(0, 10)->order('createdAt', 'DESC')->find();

Find the first one

$account = $entityManager->getRepository('Account')->where(array(
    'type' => 'Customer',    
))->findOne();
$opportunityList = $entityManager->getRepository('Account')->findRelated($account, 'opportunities');

Relate entities

$entityManager->getRepository('Account')->relate($account, 'opportunities', $opportunity);

or

$entityManager->getRepository('Account')->relate($account, 'opportunities', $opportunityId);

Unrelate entities

$entityManager->getRepository('Account')->unrelate($account, 'opportunities', $opportunity);

or

$entityManager->getRepository('Account')->unrelate($account, 'opportunities', $opportunityId);