+1 (408) 320-0380

ORM: How to manage entities in your code

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 entity

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

or

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

Store entity

$entityManager->saveEntity($account);

or

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

Remove entity

$entityManager->removeEntity($account);

or

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

Find entities

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

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

Find first entity

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

Find related entities

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

Relate two entities

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

or

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

Remove relation

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

or

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

Afterword

These are not all abilities of EntityManager. But in most cases they will be enough.

One comment on “ORM: How to manage entities in your code
  1. worldmiros says:

    What is the assigned field of $accountId?

Leave a Reply

Your email address will not be published. Required fields are marked *

*